Rust names are immutable by default. mut allows reassignment, and a second let shadows a name with a new binding.

Program

Play the program to watch count change by reassignment and then by shadowing.

variables.rs
Replay: real traced execution (multi-file project)
fn main() {
    let mut count = 1;
    count = count + 2;
    let count = count * 10;
    println!("{count}");
}
  1. count ← 1

    1fn main() {2    let mut coun→ 1t = 1;3    count = coun→ 3t + 2;4    let coun→ 30t = count * 10;5    println!("{count}");6}
    output30

Follow the Count

  1. let mut count = 1 starts count at 1.
  2. count = count + 2 updates the same mutable value to 3.
  3. let count = count * 10 makes a new shadowing value.
  4. The new count is 30.
  5. println! prints 30. | step | count value | | --- | --- | | start | 1 | | after + 2 | 3 | | after shadowing * 10 | 30 | | printed output | 30 |
mut `let mut` allows a binding to be reassigned.
reassignment `count = count + 2` updates the existing mutable value.
shadowing A new `let count` creates a fresh binding that hides the old one.

Exercise: variables.rs

Reproduce the output 30, then change the starting count and predict the final shadowed value before running it.