Index
Definition
Shadowing allows a variable to be re-declared in the same scope with the same name
Variable re-declared in a different scope
- when we exit the scope the original variable stay intact
let x = 5;
{
let x = "ciao";
println!("{x}"); // Output: ciao
}
println!("{x}"); // Output: 5
Variable re-declares in the same scope
- The original variable it’s overwritten by the new one
let x = 5;
println!("{x}"); // Output: 5
let x = "ciao";
println!("{x}"); // Output: ciao
Nota:
We are not mutating the original variable but we a declaaring a new variable we the same name of the old one
Example of re-declaration:
let x = 5; let x = "Hello";
Example of mutation:
let mut x = 5; x = 6;