Currently, I'm learning the Lifetimes topic in Rust.
And I kind of get it, but recently I've came across this simple code:
#[derive(Debug)]
struct Test {
val: i32
}
fn main() {
let a:&Test;
let b = 32;
a = &Test {
val: b
};
println!("{:?}", a.val);
}
But it won't compile, with the respective error provided:
error[E0716]: temporary value dropped while borrowed
I know how to fix it & I do understand, that a temporary was created at line 10 and will be destroyed at the end of the statement at line 12.
(also the compiler itself states the same)
What I don't understand, it's why the following code actually will compile?
#[derive(Debug)]
struct Test {
val: i32
}
fn main() {
let a:&Test;
let b = 32;
a = &Test {
val: 5
};
println!("{:?}", a.val);
}
Only struct initialization values has been changed.
The val
was b
and now it's 5
.
My guess is that the value of b
, which is now owned by val
field of our struct instance will be dropped at the end of the statement.
And therefore we will end up with the dangling reference.
Oh ... and one more interesting example.
#[derive(Debug)]
struct Test {
val: i32
}
fn main() {
let a:&Test;
let b = 32;
let a = &Test {
val: b
};
println!("{:?}", a.val);
}
This will also successfully compile.
It's the same as the first example, but we shadowing the a
variable with let
.
So, my fellow rustaceans ... why it's working this way?