Shadowing
Shadowing is declaring a new variable with let that reuses an existing name. The old binding still exists but is hidden, and the new one may have a completely different type.
Detailed Explanation
Write let input = "42"; and then let input: u32 = input.parse().unwrap();. That second let does not assign to the first variable. It creates a second, separate variable that happens to have the same name. From that line onward, input refers to the new one. The original is shadowed: still in memory, still owning its data, but no longer nameable.
The difference from mutation is worth stating precisely, because it is the whole point.
Mutation (let mut x, then x = ...) | Shadowing (let x, then let x = ...) | |
|---|---|---|
| Number of variables | One | Two |
| Type may change | No | Yes |
| Works on an immutable binding | No | Yes |
| Undone when a block ends | No | Yes, the outer binding reappears |
Shadowing exists because of a tension in Rust's design. Bindings are immutable by default, and good names are scarce. Without shadowing, a three-step transformation would force you to invent input, input_trimmed, and input_parsed, or to make the binding mut and give up immutability for the rest of the function. Shadowing lets you keep one honest name for one conceptual value while its representation changes, and every intermediate binding stays immutable.
The type-changing case is where it earns its place. You are reading a port number from a config file. It arrives as a String, you trim it, you parse it into a u32. Calling all three port is accurate, because all three are the port. What changes is only the representation. The same pattern shows up when converting a Vec<String> of arguments into a parsed struct, or a &str into a validated newtype.
Shadowing is also scoped. Inside an inner block you can shadow a name, and when the block ends the outer binding comes back untouched. This is ordinary lexical scoping, and it is how a temporary alias inside a loop body does not leak out.
One consequence surprises people: shadowing a binding does not drop the old value early. The shadowed value is still owned by its now-unreachable binding and is destroyed at the end of the scope, in the normal reverse-declaration order. If the old value holds a lock or a file handle, shadowing it does not release it. Use an inner block or drop(old) if you need the release to happen at that point.
When does it read well, and when does it confuse? It reads well when the new value is the same thing in a new form, the transformation is short, and the two bindings are close together. It confuses when the name now means something different, when the shadow sits dozens of lines from the original, or when the shadowing happens inside a branch so that a reader has to track which binding is live. The worst case is an accidental shadow: you meant to assign but typed let, so your update silently applies to a fresh variable and the original keeps its stale value. The compiler usually catches this with an unused variable warning, which is one more reason to keep warnings at zero.
The runtime cost is nothing. Shadowing is a compile-time naming decision, and the optimiser treats the two bindings as it would any two variables. The cost is readability, paid only when you overuse it.
Code Examples
fn main() {
// A config value arrives as text and becomes a number, keeping one name.
let port = " 8080 ";
let port = port.trim(); // still a &str, now trimmed
let port: u16 = port.parse().expect("bad port"); // type changes: &str -> u16
println!("{}", port + 1); // prints: 8081
// Mutation could not do this: a `mut` binding keeps its type forever.
// let mut p = "8080";
// p = 8080; // error[E0308]: mismatched types
let level = 1;
{
let level = level * 10; // shadows only inside this block
println!("{level}"); // prints: 10
}
println!("{level}"); // prints: 1 — the outer binding is untouched
}fn main() {
let raw = String::from("hello");
let raw = raw.len(); // the String is shadowed, but NOT dropped here
println!("{raw}"); // prints: 5
// The original String is freed at the end of main, not at the shadowing line.
// If you need the value gone now, be explicit:
let file = std::fs::File::open("Cargo.toml");
let file = file.is_ok(); // the File handle is still open behind the scenes
println!("{file}"); // prints: true
}Common Gotchas
An accidental `let` creates a new variable, not an update
inside a loop, `let total = total + n;` shadows rather than accumulates, and the running sum resets every iteration. The `unused variable: total` warning is your only hint, so do not ignore warnings.
Shadowing does not release resources
a shadowed lock guard, file handle, or `MutexGuard` lives until the end of its scope. Hiding the name does not run `Drop`. Use a nested block or `drop()` when the release point matters.
Shadowing works on function parameters too
`fn run(config: String) { let config = parse(config); }` is idiomatic and common, and often removes the need for a second name.
`let` patterns can shadow several names at once
destructuring a tuple with `let (x, y) = ...` shadows any existing `x` and `y`. That is usually what you want, but it makes an unintended collision easy to miss in long functions.