70 %
Chris Biscardi

Variables in Rust

Rust has one main way to declare variables. let. let is used for immutable variables and mutable variables.

rust
fn main() {
let n = 4;
let mut x = 5;
}

Shadowing

variables can be shadowed by declaring it with let again.

rust
fn main() {
let n = 5;
let n = "string";
}

Constants

const vs static RFC

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.

rust
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.

rust
static LANGUAGE: &str = "Rust";
fn main() {
println!("the language we use is {}", LANGUAGE);
LANGUAGE = "JS"; // we're switching! this is unsafe
println!("the language we use is {}", LANGUAGE);
}