liveBook · Manning

Mut keyword

As explained in Idiomatic Rust

The Rust `mut` keyword marks a binding or reference as permitting mutation.

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

How Idiomatic Rust covers it

How deep it goes
Explains default and inherited mutability, then contrasts owned values, borrowed references, and interior-mutability containers.
Examples
Uses variable shadowing, a mutable function parameter, and `RefCell` to demonstrate mutation.
What you can do after
Apply `mut` to a binding or function parameter and distinguish that from interior mutability.
How it connects
Connects mutability to ownership, borrowing, the borrow checker, interior mutability, and functional programming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.