Why can I shadow a variable which has been borrowed before? Where is the owner?

58 Views Asked by At

Trying to understand ownership and borrowing in Rust, I came across this scenario, where I create an object a (which should be the owner) and then borrow it into b. Then, I try to shadow a:

#[derive(Debug)]
struct Struct1;

#[derive(Debug)]
struct Struct2;

fn main() {
    let a = Struct1;
    let b = &a;

    let a = Struct2;
    
    println!("{:?} {:?}", a, b);
}

The problem is, I expected this to fail, but it does in fact work, with the output:

Struct2 Struct1

If I shadow a, where is the owner of the borrowed b?

2

There are 2 best solutions below

0
user1937198 On BEST ANSWER

The first a is still the owner of the Struct1, with a lifetime up until the last use within main, which is when the borrow ends when b is dropped after the println!. Shadowing creates a new binding that does not effect the previous one, other than making it invisible within the current scope.

As such this program is equivalent to (and just syntactic sugar for) a program:

#[derive(Debug)]
struct Struct1;

#[derive(Debug)]
struct Struct2;

fn main() {
    let a_1 = Struct1;
    let b = &a_1;

    let a_2 = Struct2;
    
    println!("{:?} {:?}", a_2, b);
}

where a_1 is not directly interacted with after the binding of a_2.

0
Aurel Bílý On

The owner of Struct1 is still the first a variable you created. The fact that you declared another variable which has the same name does not make a difference with respect to ownership, it only makes a difference at the syntax level in that a will refer to something else from that point on.