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
?
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
.