In Rust, you can’t change the type of a variable once it’s declared. But sometimes, you want to reuse a variable name for a new purpose without creating an entirely new variable. This is where shadowing comes in.
What is Shadowing? #
Shadowing means declaring a new variable with the same name as an existing one. The new variable shadows (hides) the old one, and from that point forward, the old variable is no longer accessible.
You use let again for shadowing — not mut.
Basic Shadowing Example #
fn main() {
let x = 5;
let x = x + 1; // shadows the previous x
let x = x * 2; // shadows again
println!("The value of x is: {}", x);
}
Code language: Rust (rust)Output:
The value of x is: 12
Explanation:
- First
x = 5 - Then we shadow it:
x = 5 + 1 = 6 - Then shadow again:
x = 6 * 2 = 12
Shadowing vs. Mutability #
- With
mut, you can change the value of a variable but not its type. - With shadowing, you can even change the type.
Example:
fn main() {
let spaces = " "; // spaces is a string slice
let spaces = spaces.len(); // now spaces is a number (usize)
println!("Number of spaces: {}", spaces);
}
Code language: Rust (rust)Output:
Number of spaces: 3
Code language: JavaScript (javascript)Here, we first store " " (a string), then shadow it with its length (an integer).
This would not be possible using mut.
When to Use Shadowing #
Useful when:
- You want to transform a value step by step.
- You want to reuse a variable name for something derived from its previous value.
- You want to change a variable’s type but keep the same name for clarity.
Not good when:
- You need to keep the old value around. In that case, give the new variable a different name.
Summary #
- Shadowing lets you reuse the same variable name.
- Achieved with
let, notmut. - Allows type changes, unlike
mut. - Old values are inaccessible after shadowing.
Was this Helpful ?