Always consider the scope

As with borrowing, we have to consider the scope to ensure that things work correctly.

The following piece of code, for example, won't work:

struct MyStruct<'a> { 
    lifea: &'a i32, 
} 
 
fn main()  
{ 
    let x;  
    {   
        let y = &5; // means let y = 5; let y = &y; 
        let f = MyStruct { lifea: y };  
        x = &f.lifea  
    }  
    println!("{}", x);  
} 
The code for this section is in the 08/lifetimescope folder of the supporting code bundle provided along with this book.

It may not seem obvious at first why this should not work. In terms of scope, f is created after y, so is in the scope of y and y is created within the scope of x. Or is it?

When the code is built, we will get the following output:

The error will be the x = &f.lifea, as we attempted to assign a value of something about to go out of scope.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset