Page Content

Tutorials

What is shadowing in Rust?

shadowing in rust is a feature allows you to declare a new variable with the same name as a previous variable. When this occurs, “Rustaceans” assert that the second variable shadows the first. This means the second variable’s value is what is seen when the variable name is used. You achieve this goal by using the let keyword again with the same variable name. In effect, the second variable overshadows the first within its scope.

Example:

fn main(){
let x = 5; // First variable x
let x = x + 1; // Second variable x, shadows the first
// x is now 6 here
print!("the value of x is:{}",x)
}

Output:

the value of x is:6

Shadowing is different from marking a variable as mut. If you by chance try to reassign to a variable without using the let keyword again, you will get a compile-time error. By using let, you can perform transformations on a value and then have the variable be immutable after  transformations are complete.

Another difference is shadowing successfully creates a new variable. It allows you to change the type of the value while reusing the same variable name.

Example:

fn main(){
let spaces = "    "; // spaces is a string slice
let spaces = spaces.len(); // shadows the string slice 'spaces' with a number (usize)
// spaces is now 3 here
println!("The value is: {}",spaces );
}

Output:

The value is: 4

Shadowing is also affected by possibilities. A variable is valid from its declaration until the end of the current scope. A variable shadowed within an inner scope will only be in effect until that inner scope ends.

Example:

fn main() {
    let x = 1;
    {
        println!("before being shadowed: {}", x);
        // This binding *shadows* the outer one
        let x = "abc";
        println!("shadowed in inner block: {}", x);
    }
    println!("outside inner block: {}",x);
    // This binding *shadows* the previous binding
    let x= 2;
    println!("shadowed in outer block: {}", x);
}

Output:

before being shadowed: 1
shadowed in inner block: abc
outside inner block: 1
shadowed in outer block: 2

Rust Programming: