Shadowing
We can declare a new variable with the same name as a previous variable. Rustaceans say that the first variable is shadowed by the second, which means that the second variable is what the compiler will see when you use the name of the variable. In effect, the second variable overshadows the first, taking any uses of the variable name to itself until either it itself is shadowed or the scope ends. We can shadow a variable by using the same variable’s name and repeating the use of the let keyword as follows:
Filename: src/main.rs
fn main() {
let a=5;
println!("The value of a is: {a}");
let a = 15;
println!("The value of a is: {a}");
}
Output:
The value of a is: 5
The value of a is: 15
Last updated