In the rust code below, I would expect both calls to pass_through
to fail, since both a
and b
go out of scope at the end of the inner block. However, for some reason the following happens:
- Creating a reference to an
NC
value and and storing that reference ina
allows it to live long enough. - Creating an
NC
value and storing it inb
, then taking a reference tob
for the function parameter causes an error.
#[derive(Debug)]
struct NC(i32);
fn pass_through(x: &NC) -> &NC {
x
}
fn main() {
let a2: &NC;
let b2: &NC;
{
let a = &NC(1);
a2 = pass_through(a); // Works fine
let b = NC(2);
b2 = pass_through(&b); // Error, borrowed value does not live long enough
}
println!("a2 - {:?}", a2);
println!("b2 - {:?}", b2);
}
Why does the borrow checker treat these two cases differently?