Variable Shadowing

Hi All,

I have started Rust 2 days ago and I am pacing myself through the rust book. While going through the "Variables and Mutability" section, the following lines are written about variable shadowing and I am quoting the lines below:

" The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name."

Going by the above text, I have few questions:

  1. In a given scope, if we shadow a variable, a new variable is created. What happens to the
    variable that was shadowed? Is it still accessible or it gets destructed automatically as soon
    as it gets shadowed?

  2. What is meant by "reuse the same name"? Is the name of a variable indicates a memory
    address which the compiler can reuse for shadowed variables? Does shadowed variables
    share same memory address ?

  3. What happens to the data that a shadowed variable holds?

  4. Why shadowing in same scope was designed in Rust? What specific benefits we derive
    when we use shadowing in same scope?

  1. It isn't destructed immediately, you just can't refer to it by the shadowed name anymore.

  2. The name is just a binding. A shadowed variable is a different variable, just with the same name.

  3. Nothing - it stays around the same as if you didn't shadow it.

  4. Convenience. There are times where you want to transform data and don't need the original value - turning some serialized data into parsed data, for instance. It would be annoying to have to come up with a new name to represent the new value.

In effect, shadowing in the same scope is basically the same as if you introduced a new scope that extends to the end of the current scope:

{
    let x = 123;
    let x = 234;
    println!("{}", x);
}

// becomes

{
    let x = 123;
    {
        let x = 234;
        println!("{}", x);
        // the outer x is still around, we just can't refer to it right now
    }
}
3 Likes

Thanks for the explanation!

Shadowing can also be used to change mutability, so that an object is mutable (unique) during construction and then shadowed by a same-name redeclaration of the object as immutable (sharable). From that point onward, within the scope of the shadowing redeclaration, the object can't be modified but can be shared.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.