Hi,
in the rust book it is not explained, why this code is not valid:
fn main() {
let y: &i32;
let x = 5;
y = &x;
println!("{}", y);
}
The compiler says, that x does not live long enough, but why? Normally it would last until the end of the scope, but if y is declared before x, this is apparently not the case anymore, but I just don't get it.
Anyone?
Thanks in adavance!
Stefano
1 Like
The problem is that variables are destroyed (dropped) in reverse declaration order so x
is dropped before y
(because it is declared second). Your program is really:
fn main() {
{
let y: &i32;
{
let x = 5;
y = &x;
println!("{}", y);
// End of visible scope
}}
}
Technically, this is mentioned in the Drop section but it should probably also be mentioned in the lifetime section. /cc @steveklabnik?
1 Like
Yes, it might deserve mention there too
Hi stebalien,
this is a good explanation. Thx!