Make change explicit.
Separate changing a value from introducing a new binding.
01 Understand the contract
A let binding is immutable unless you opt into mut. Mutation changes the value in an existing binding, so its type stays fixed. Shadowing creates another binding with the same name and can change the type. This is useful when turning raw input into a validated representation. A const is a named compile-time value that needs an explicit type. Prefer the least changeable representation that fits the work: immutable values are easier to reason about, while a small local mutable accumulator is often exactly right.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
const MAX_RETRIES: u32 = 3;
fn main() {
let mut attempts = 1;
attempts += 1;
let input = " 42 ";
let input: u32 = input.trim().parse().expect("valid number");
println!("attempts={attempts}/{MAX_RETRIES}, input={input}");
}attempts=2/3, input=42
- 1
MAX_RETRIES has a type and a constant initializer.
- 2
mut allows attempts to be updated in place.
- 3
The second input shadows a string slice with a parsed u32.
cargo run -p lesson_variables03 Mind the boundary
04 Your next build
Start a mutable score at 10, add 5, then shadow a string with its character count.
Reveal one possible solution +
fn main() {
let mut score = 10;
score += 5;
let label = "rust";
let label = label.chars().count();
assert_eq!(score, 15);
assert_eq!(label, 4);
}05 Check your reasoning
Can shadowing introduce a different type?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.