0
0
Rustprogramming~10 mins

Variable shadowing in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variable shadowing
Declare variable x = 5
Shadow x with new x = x + 1
Shadow x again with new x = x * 2
Use x (final shadowed value)
End of scope
Variable shadowing means reusing the same name for a new variable that hides the old one temporarily.
Execution Sample
Rust
fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;
    println!("{}", x);
}
This code shows how the variable x is shadowed twice, changing its value each time.
Execution Table
StepCode LineVariable x ValueActionOutput
1let x = 5;5Declare x with value 5
2let x = x + 1;6Shadow x with 5 + 1
3let x = x * 2;12Shadow x with 6 * 2
4println!("{}", x);12Print final x value12
💡 Program ends after printing the final shadowed value of x, which is 12.
Variable Tracker
VariableStartAfter Shadow 1After Shadow 2Final
x561212
Key Moments - 3 Insights
Why does the value of x change even though we never used a different variable name?
Because each 'let x = ...' creates a new variable that hides the old one temporarily, as shown in execution_table steps 2 and 3.
Is the original x (with value 5) lost after shadowing?
Yes, after shadowing, the old x is hidden and replaced by the new x, but only inside the current scope, as seen in variable_tracker.
Can we use the old x after shadowing?
No, once shadowed, the old x is inaccessible until the scope ends, so the code always uses the latest x value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after the first shadowing (step 2)?
A5
B6
C12
D1
💡 Hint
Check the 'Variable x Value' column at step 2 in the execution_table.
At which step does the variable x get its final value before printing?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Variable x Value' column and the 'Action' description in the execution_table.
If we removed the second shadowing (step 3), what would be printed?
A6
B5
C12
DError
💡 Hint
Refer to the variable_tracker and imagine skipping the last shadowing step.
Concept Snapshot
Variable shadowing in Rust:
- Use 'let' with the same name to create a new variable.
- New variable hides old one temporarily.
- Allows changing value without mut.
- Old variable inaccessible until scope ends.
- Useful for transformations and cleaner code.
Full Transcript
This example shows variable shadowing in Rust. First, x is declared as 5. Then, x is shadowed by a new x equal to 5 plus 1, so 6. Next, x is shadowed again by a new x equal to 6 times 2, so 12. Finally, the program prints 12. Each shadowing creates a new variable with the same name that hides the previous one. This lets us change the value without using mut. The old x values are hidden and cannot be accessed after shadowing. This is useful for step-by-step value changes in a clean way.