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
ais still the owner of theStruct1, with a lifetime up until the last use within main, which is when the borrow ends whenbis dropped after theprintln!. 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:
where
a_1is not directly interacted with after the binding ofa_2.