Let's revisit some old code

Back in Chapter 4, Conditions, Recursion, and Loops, we had some code that looked like this:

let x = 2; 
let y =  
    { 
        let x_squared = x * x; 
        let x_cube = x_squared * x; 
        x_cube + x_squared + x 
    }; 

It was explained that what it did was assign the result of x_cube + x_squared + x to y. If, outside of that, we attempted to access either x_squared or x_cubed, then we wouldn't be able to, as they only existed within the scope of that calculation for y.

Consider, then, what would happen if we made y a reference and tried to point it to a temporary value:

    // 05/refs-1/src/main.rs
fn main() { let x = 2; let y: &i32; { let x_squared = x * x; let x_cube = x_squared * x; y = &(x_cube + x_squared + x);
// this value goes away after this line }; println!("Y = {}", *y); }

We are assigning y to the value of a variable that only exists in a small scope (the temporary unnamed value of the computation), then we're trying to access that value 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.

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

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