Rust bindings are immutable by default; `mut` opts a binding into mutation. Mutability is inherited by data inside an immutable structure, while interior-mutability containers provide a separate way to mutate contained data. section 9.4
The effect of `mut` depends on what is being bound:
- A mutable binding can be changed; shadowing an immutable binding with `let mut` creates a mutable binding. section 9.5
- A function can take an owned value as a mutable parameter, but changing its binding does not change the caller’s binding; borrowed data cannot be made mutable this way. section 9.5
- `Cell`, `RefCell`, and `OnceCell` allow interior mutability inside an immutable container; `Cell` replaces its value rather than exposing a mutable reference. section 9.4
Listing 9.1 Basics of immutability in Rust
let x = 1; dbg!(x); let y = x + 1; // y = 2 dbg!(y); // x += 1; #1 // error: cannot assign twice to immutable variable `x` let mut x = x; // x = 1 #2 x += 1; // x = 2 dbg!(x);
See `let mut x = x` shadow an immutable binding before `x` is incremented. section 9.5
