[solved] Reference and Borrowing: Question about Life Time


#1

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


[solved] Is it `z` who does not live long enough or rather is it `&z`?
#2

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?


#3

Yes, it might deserve mention there too


#4

Hi stebalien,
this is a good explanation. Thx! :slight_smile: