Sub topic 4
Shadowing versus mutation
This chapter assumes you can declare bindings with let, know that bindings are immutable by default, and have seen mut. You should also be able to run a program with cargo or rustc and read a basic compiler error.
What shadowing is
Shadowing means declaring a new binding with let that reuses the name of an earlier binding. The earlier binding still exists, but the name now refers to the new one. Mutation is different. It changes the value stored in one existing binding, and that requires mut.
fn main() {
let spaces = " ";
let spaces = spaces.len();
println!("spaces = {spaces}");
let x = 5;
let x = x * 2;
{
let x = x + 1;
println!("inner x = {x}");
}
println!("outer x = {x}");
}This prints spaces = 3, inner x = 11, and outer x = 10.
- The first
spacesis a&str. The secondspacesis ausize. Shadowing created a new binding, so the type could change. xis first 5, then shadowed to 10 in the same scope.- The inner
let x = x + 1shadows only until the closing brace. Afterward, the name refers to the outer binding again, whose value is still 10.
How the two differ
| Feature | Shadowing | Mutation |
|---|---|---|
| Syntax | `let x = ...;` again | `x = ...;` on a `let mut` binding |
| Needs `mut` | No | Yes |
| Can change the type | Yes | No |
| Creates a new binding | Yes | No |
| Ends at | End of the enclosing block (for the inner binding) | Never, until the binding goes out of scope |
Why the type rule matters
A mut binding keeps its type for its whole life. Trying to change it is a compile error.
fn main() {
let mut spaces = " ";
spaces = spaces.len(); // error[E0308]: mismatched types
println!("{spaces}");
}The compiler rejects this because spaces was inferred as &str, and a usize cannot be stored in it. Shadowing avoids the problem without inventing names such as spaces_str and spaces_len.
Choosing between them
Use shadowing when you transform a value in steps and the old form is no longer needed. Parsing input is the common case.
fn main() {
let input = "42";
let input: u32 = input.parse().unwrap();
let input = input + 1;
println!("{input}");
}After the last line, the binding is immutable again. Nothing can change input later by accident. This is the main advantage over let mut.
Use mut when the value is updated repeatedly, such as a counter in a loop. Shadowing inside a loop body does not carry over to the next iteration, so it cannot accumulate a total.
fn main() {
let mut total = 0;
for n in 1..=3 {
total += n;
}
println!("total = {total}");
}Common errors
- Expecting an inner shadow to persist. A
letinside a block,if, or loop body is gone after the block ends. The outer value is unchanged. - Forgetting
let. Writingx = x * 2;on an immutablexgiveserror[E0384]: cannot assign twice to immutable variable. Writinglet x = x * 2;is legal. - Shadowing by accident. If you retype
letwhere you meant to assign, you create a new binding. When that happens inside a block, the outer variable keeps its old value, and the compiler may warn about an unused variable. - Confusing readers. Shadowing the same name many times in a long function makes it hard to tell which value a line uses. Give the name a new meaning only when the old value is truly finished with.
Exercise
This program does not compile. Fix it in two ways: once with shadowing and once with mut. Which fix works, and why does the other one fail?
fn main() {
let data = "7";
data = data.parse::<i32>().unwrap();
println!("{data}");
}
Show answer
Shadowing works: let data = "7"; let data = data.parse::<i32>().unwrap();. The new binding can have type i32. Adding mut fails because a mut binding keeps its type &str, so assigning an i32 gives a mismatched types error (E0308). With mut you would need a separate name, such as let n = data.parse::<i32>().unwrap();.