Shadowing (Rust)
Shadowing is re-declaring a variable with the same name using let. The new binding replaces the old one within the scope, and it may even have a different type.
Rust
Unlike mutation, shadowing creates a new variable that happens to reuse the name. This lets you transform a value while keeping the binding immutable, and crucially lets you change its type — for example parsing a String into a number under the same name.
Shadowing is scoped: a shadow inside an inner block disappears when that block ends, restoring the outer variable. This is a frequent and idiomatic Rust pattern, not a code smell.
Use shadowing when you want successive transformations of a value; use mut when you genuinely need to mutate the same storage in place (such as a counter in a loop).
Syntax
let x = 5;
let x = x + 1; // shadows, new immutable binding
let x = "now text"; // can even change typeExamples
Rust
fn main() {
let spaces = " ";
let spaces = spaces.len(); // &str -> usize
println!("{}", spaces);
}Output:
3