Sub topic 4
Shadowing versus mutation
This chapter assumes you can write and run a basic Rust program with cargo run or rustc. It also assumes you know how let creates a binding and how mut allows reassignment. Here you will learn what shadowing is, how it differs from mutation, and when to use each.
What shadowing is
A let statement creates a new binding. If you write let with a name that is already in scope, the new binding hides the old one. This is called shadowing. The old value still exists in memory until its owner is dropped, but the old name no longer refers to it in that scope.
fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("x = {x}");
}This prints x = 12. Three separate bindings named x are created. Each let reads the previous x on its right-hand side, then introduces a new x. None of the bindings is declared mut, so none of them can be reassigned. The program still "changes" the value of x, but only by creating new bindings.
Shadowing can change the type
A mut binding has one type for its whole life. A shadowing let creates a fresh binding, so it can have a different type.
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}");
}The first spaces is a &str. The second is a usize. The program prints spaces = 3, then inner x = 11, then outer x = 10.
Try the same idea with mut and the compiler rejects it:
fn main() {
let mut spaces = " ";
spaces = spaces.len();
println!("{spaces}");
}The compiler reports error[E0308]: mismatched types. It expected &str because that was the type of the original binding, and it found usize. Assignment never changes a binding's type.
Scope: shadowing lasts until the end of the block
A shadowing binding hides the old one only inside the block where it is declared. When that block ends, the inner binding goes out of scope and the outer name is visible again. In the example above, the inner x is 11 and the outer x is still 10 after the inner block closes.
Compare this with mutation inside a block:
fn main() {
let mut y = 10;
{
y += 1;
}
println!("y = {y}");
}This prints y = 11. Mutation changes the one existing binding, so the change survives the end of the inner block. Shadowing does not survive it.
Comparing the two techniques
| Aspect | Shadowing (`let x = ...`) | Mutation (`let mut x`, then `x = ...`) |
|---|---|---|
| Creates a new binding | Yes | No |
| Can change the type | Yes | No |
| Needs `mut` | No | Yes |
| Result is immutable afterwards | Yes, unless the new `let` uses `mut` | No, the binding stays mutable |
| Effect at end of block | Old binding becomes visible again | Change persists |
| Works for fields and elements | No, it only replaces whole bindings | Yes, such as `v[0] = 1` or `p.x = 1` |
The last row matters. You cannot shadow a field or a vector element. If you want to change part of a value in place, you need a mutable binding.
Using shadowing to transform a value
A common pattern is to take input, convert it step by step, and keep the same name. The raw form is no longer needed, so reusing the name avoids inventing names such as input_str and input_num.
fn main() {
let input = " 42 ";
let input = input.trim();
let input: u32 = input.parse().unwrap();
let input = input * 2;
println!("{input}");
}This prints 84. After the last let, the final input is immutable. That is a real benefit. The value was prepared in several steps, and from then on the compiler guarantees nobody changes it.
You can get the same safety without reusing the name by wrapping the steps in a block:
fn main() {
let input = {
let raw = " 42 ";
let n: u32 = raw.trim().parse().unwrap();
n * 2
};
println!("{input}");
}Both styles are common. Shadowing is shorter. The block makes the temporary names explicit and ensures they cannot be used later.
Using mutation when state really changes
Shadowing is a poor fit when a value is updated repeatedly in a loop. Each iteration of a loop body is its own scope, so a shadowing let inside the loop does not carry over to the next iteration.
This version has a bug:
fn main() {
let total = 0;
for i in 1..=3 {
let total = total + i;
println!("inside: {total}");
}
println!("outside: {total}");
}It prints inside: 1, inside: 2, inside: 3, then outside: 0. Each iteration reads the outer total, which is always 0, and creates a new inner total that disappears at the end of the iteration. The compiler may also warn that the outer total is never mutated as the programmer intended. The program compiles, so the mistake is silent.
The correct version uses mut:
fn main() {
let mut total = 0;
for i in 1..=3 {
total += i;
}
println!("total = {total}");
}This prints total = 6. The loop must update one binding that lives outside the loop body, and only mutation can do that.
Shadowing and mutability are independent
A shadowing let may add or remove mut. This lets you freeze a value after a phase of mutation.
fn main() {
let mut data = vec![3, 1, 2];
data.sort();
let data = data;
println!("{data:?}");
// data.push(4); // error[E0596]: cannot borrow `data` as mutable
}The let data = data; line moves the vector into a new immutable binding. From that point on, data.push(4) is rejected. This is a short way to say "I am finished changing this."
The reverse also works. let mut x = x; turns an immutable parameter or binding into a mutable one inside a function without touching the caller's variable.
Shadowing and ownership
Shadowing does not drop or free the old value immediately. A shadowed value lives until the end of its scope, unless it was moved out.
fn main() {
let s = String::from("hello");
let s = s.len();
println!("{s}");
}Here s.len() only borrows the String. The first s is hidden but still alive, and its memory is freed at the end of main. If you want the old value gone sooner, move it into something or place it in an inner block.
When a value is moved, as in let data = data; above, the old name no longer owns anything, so there is no duplicate to worry about.
Edge cases and common errors
- Shadowing a function parameter. Parameters are bindings, so you can write
let n = n.abs();at the top of a function. This is allowed. - Shadowing in
matchandif let. Patterns introduce new bindings. Inif let Some(x) = x { ... }, the innerxis the unwrapped value and the outerxis theOption. The inner name only exists inside theif letblock. - Shadowing a
constorstatic. Aletpattern cannot reuse the name of a constant. A pattern that names a constant is treated as a comparison against that constant, which is not what you want. Choose a different name. - Unused shadowed values. If you shadow a binding and never read the old one, the compiler may warn
unused variable. Prefix a name with an underscore, such as_old, to silence it when that is intentional. - Readability. Shadowing many times, or across a long function, makes it hard to know which
xa line refers to. If you need to remember three different meanings of one name, use distinct names.
Choosing between them
Use shadowing when:
- You convert a value to a new form and the old form is no longer needed.
- The type changes, such as
&strtou32. - You want the final result to be immutable after a preparation phase.
Use mut when:
- A value is updated repeatedly, as in a loop or an accumulator.
- You change part of a value in place, such as a vector element or a struct field.
- The update must be visible outside the block where it happens.
If both would work, prefer the one that keeps the binding immutable at the end. That gives the compiler, and the next reader, the strongest guarantee.
Exercise
What does this program print, and why? fn main() { let x = 1; let x = x + 1; { let x = x * 10; println!("{x}"); } println!("{x}"); }
Show answer
It prints 20, then 2. The first shadowing makes x equal to 2. Inside the block, a new x is created as 2 * 10 = 20, and that is printed. When the block ends the inner x is gone, so the outer x, which is still 2, is printed.
Exercise
A learner writes let mut count = "0"; count = count.len(); and gets a compile error. Explain the error and show a fix that uses shadowing.
Show answer
The error is E0308, mismatched types. A binding keeps one type, and count is a &str, so it cannot be assigned a usize. Shadowing creates a new binding, so let count = "0"; let count = count.len(); compiles, and the second count is a usize.
Exercise
Why does the loop let total = 0; for i in 1..=3 { let total = total + i; } fail to accumulate a sum, and how do you fix it?
Show answer
The let inside the loop body creates a new total in each iteration that ends with that iteration. The outer total is never changed and stays 0. Declare it as let mut total = 0; and write total += i; inside the loop.