Beginner Fundamentals
Shadowing
Shadowing lets you declare a new variable with the same name as a previous one using let again. The new declaration replaces the old binding within its scope.
Basic shadowing
fn main() {
let x = 5;
let x = x + 1; // shadows the first x, now 6
let x = x * 2; // shadows again, now 12
println!("{}", x); // 12
}
Each let creates a brand new variable, so the value can be transformed step by step.
Changing the type
Because shadowing creates a new variable, you can even change the type while keeping the name.
fn main() {
let spaces = " "; // &str
let spaces = spaces.len(); // usize
println!("{}", spaces); // 3
}
This would not work with mut, since a mutable variable cannot change its type.
Shadowing vs mut
mut: same variable, value changes, type stays the same.- Shadowing: a new variable each time, type can change.
Shadowing is useful for transforming a value while reusing a meaningful name.