Rust has one main way to declare variables. let
. let
is used for immutable variables and mutable variables.
fn main() {let n = 4;let mut x = 5;}
variables can be shadowed by declaring it with let
again.
fn main() {let n = 5;let n = "string";}
Rust also has Constants, which live for the lifecycle of the entire program and are unchangeable. This makes then useful for values that don't change, like the speed of light or the number of squares on the tic-tac-toe board.
Constants must have types.
const THRESHOLD: i32 = 10;fn main() {println!("the threshold is {}", THRESHOLD);}
static
can be used in addition to const
, which declares a possibly mutable global variable that has a static lifetime. Accessing or modifying a mutable static variable is unsafe.
static variables must have types.
static LANGUAGE: &str = "Rust";fn main() {println!("the language we use is {}", LANGUAGE);LANGUAGE = "JS"; // we're switching! this is unsafeprintln!("the language we use is {}", LANGUAGE);}