Shadowing
In the previous lesson, mut opened the lid of a box, and you could put new values into it. Rust has a second way to get a new value under the same name: declare the variable again.
Picture a new box with the same label placed in front of the old one. When you look for the box by its name, you see only the front one. The old box has not gone anywhere and stands behind, but you can no longer reach it by its name.
fn main() {
let price = 100;
let price = price * 2;
println!("{price}"); // 200
}Let's go line by line:
let price = 100;creates the variablepricewith the value100.- In the second line, to the right of
=, the namepricestill leads to the old box, soprice * 2equals200. - On the left,
let pricecreates a new variable with the same name and puts200in it. println!finds the front box by its name and prints200.
A new variable with a name already in use hides the old one. This is called shadowing. A second let with the same name is not an error but a common technique in Rust. Both price variables are immutable, and neither of them changed.
Shadowing in a block
Curly braces inside a function form a block. A variable declared in a block lives until the block's closing brace }. If you shadow an outer variable inside a block, the new box stands in front of the old one only until the end of the block:
let x = 10;
{
let x = x + 1;
println!("{x}"); // 11
}
println!("{x}"); // 10let x = 10;creates the outerx.- Inside the block,
let x = x + 1;reads the outerxand creates a new one with the value11. println!in the block sees the front box and prints11.- At
}the block ends, and its variablexdisappears with it. - The last
println!sees the outerxagain and prints10.
Shadowing and mut
From the outside, shadowing looks like mut: a new value appears under the same name. But they work differently:
mutchanges the value in the same box;- shadowing puts up a new box, and the old one stays behind it with its own value.
Step through the program and watch the boxes: a changes in place, and each new b stands in front of the previous one.
1fn main() {2 let mut a = 5;3 a = a * 2;4 let b = 5;5 let b = b * 2;6 println!("{a} {b}");7 {8 let b = b + 1;9 println!("{b}");10 }11 println!("{b}");12}
let mut creates the box a with an open lid and puts 5 in it.
One more thing follows from this difference: shadowing can change the type. A new box can have a different shape, while a box with an open lid keeps its shape:
let spaces = " ";
let spaces = spaces.len();
println!("{spaces}"); // 3The first spaces is text made of three spaces. The second one is already a number: spaces.len() returns the length of that text. A dot after a value asks it for an action; here len() counts the length.
With mut this does not work: let mut count = " "; count = count.len(); does not compile and gives error[E0308]: mismatched types. Shadowing is handy when a value changes its form but keeps its meaning: there is no need to invent a second name.
Here the box analogy falls short. A real box that was pushed to the back can be reached by hand. But you cannot reach a shadowed variable by its name while a new one stands in front of it.
This question comes up in almost every interview: how does shadowing differ from mut? The answer:
- shadowing creates a new variable, while
mutchanges an existing one; - shadowing can change the type, while
mutcannot; - after shadowing, the variable is immutable again unless you write
let mut.
Common mistake
The goal was to change the outer variable inside a block, but let was written out of habit:
fn main() {
let mut total = 10;
{
let total = total + 5; // ✗
println!("{total}"); // 15
}
println!("{total}"); // 10
}warning: variable does not need to be mutableThe program builds and prints 15 and then 10. The let in the block created a new total, and it disappeared at }. Nobody changed the outer total, which is why the compiler warns that it does not need mut. To change the outer variable, remove the let: total = total + 5;.
Key points
- A second
letwith the same name creates a new variable, and the old one stays behind it. mutchanges the value in the same variable, while shadowing creates a new one and can change the type.- Shadowing in a block lasts until its
}; after it, the name leads to the outer variable again.