Basics
Variables
Mutability and Shadowing
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}");
}
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
let mut count = 1startscountat1.count = count + 2updates the same mutable value to3.let count = count * 10makes a new shadowing value.- The new
countis30. println!prints30. | 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.