The lifetime

Let's consider another piece of code which won't work:

let varname: &f32; 
{ 
    let x = 3.14f32; 
    varname = &x; 
} 
println!("varname = {}", varname); 

When trying to build this piece of code, the compiler will complain as follows:

You may recall that we had something similar to the following piece of code back in Chapter 4, Conditions, Recursion, and Loops:

let y: &f32; 
{ 
    let x_squared = x * x; 
    let x_cube = x_squared * x; 
    y = &(x_cube + x_squared + x); 
}; 
println!("Y = {}", *y); 

In Chapter 5, Memory Management, we then explained why the preceding code would not work.

We are assigning y to the value of a variable that only exists in a small scope and then trying to access that value, which is giving rise to undefined behavior. As we've seen, the Rust compiler will do everything it can to prevent this sort of error. In this case, the compiler keeps track of each and every reference and fails to build if a reference lasts longer than the pointer in use.

We have the same happening here: varname is declared before x; therefore, it lives longer than x, which is what gives rise to the error.

The preceding code is a simple demonstration of a lifetime, but it's not as simple as that.

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

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