Variable shadowing lets you reuse the same name for a new variable. It helps keep your code simple and clear without making new names.
0
0
Variable shadowing in Rust
Introduction
When you want to change a variable's value but keep the same name.
When you want to convert a variable's type but keep the name.
When you want to update a variable step-by-step in a calculation.
When you want to limit a variable's scope to a smaller block.
When you want to avoid creating many different variable names.
Syntax
Rust
let x = value1;
let x = value2; // shadows previous xShadowing uses let again with the same variable name.
The new variable replaces the old one in the current scope.
Examples
This example adds 1 to x by shadowing it with a new value.
Rust
let x = 5; let x = x + 1; println!("{}", x);
This example changes
spaces from a string to a number using shadowing.Rust
let spaces = " "; let spaces = spaces.len(); println!("{}", spaces);
This example shows shadowing inside a smaller block, keeping outer x unchanged.
Rust
let x = 10; { let x = 20; // shadows outer x only inside this block println!("{}", x); } println!("{}", x);
Sample Program
This program shows how variable shadowing works in Rust. We reuse the name x to hold new values in the same and inner scopes.
Rust
fn main() {
let x = 5;
println!("First x: {}", x);
let x = x + 10; // shadowing x
println!("Second x: {}", x);
{
let x = x * 2; // shadowing inside block
println!("Inner block x: {}", x);
}
println!("Outer x after block: {}", x);
}OutputSuccess
Important Notes
Shadowing is different from mutability. Shadowing creates a new variable, mutability changes the same variable.
You can shadow a variable with a different type, which mutability does not allow.
Shadowing helps keep code clean by reusing names without confusion.
Summary
Variable shadowing lets you reuse the same name for a new variable.
It helps update values or change types without new names.
Shadowing works in the same or inner scopes, replacing the old variable.