Variable shadowing
-
let
-
We can declare the same variable multiple time using the
let
keyword. -
The 2nd and subsequent declarations hide (shadow) the previous ones.
-
If this happened inside a block then when the shadowing version of the variable goes out of scope the previous value becomes visible again. (Observe, the last line being 6.)
fn main() { let x = 5; println!("x={x}"); let x = x + 1; println!("x={x}"); { println!("x={x}"); let x = x * 2; println!("x={x}"); } println!("x={x}"); }
x=5
x=6
x=6
x=12
x=6