Rust Variables Are Immutable Unless Declared mut

In progress

In Rust, let creates a binding that can't be reassigned; you opt into change with let mut. Making mutation the explicit exception removes a whole class of bugs, lets data be shared between threads safely, and gives the compiler more room to optimise.

let, let mut and const

let players = 21;
players = 23;          // error: cannot assign twice to immutable variable

let mut score = 21;
score = 23;            // fine

let (john, david) = (33, 21);   // destructuring a tuple

const MAX_PLAYERS: u32 = 22;     // compile-time constant, type required, never mut

Why Immutable by Default

  • Safety: a value nobody can change can't be changed by mistake somewhere else.
  • Concurrency: immutable data can be read from many threads without locks.
  • Speed: the compiler can optimise around values it knows won't change.

Shadowing Is Not Mutation

let spaces = "   ";
let spaces = spaces.len();   // a new variable with the same name, even a new type

References

Review cards

Flashcard Why is making mutation explicit in Rust considered a good practice?

Making mutation explicit in Rust helps catch bugs early, ensures thread safety, and allows the compiler to perform optimizations more effectively.