singularity

Lifetimes

Lifetimes and Borrow Checker

use rand::Rng;  
let mut x = Box::new(42.0);
let r = &x; // 1 Lifetime starts = 'a
if rand::thread_rng().gen_bool(0.5) {
    *x = 84.0; 
    // 2 no conflicting borrows found, r is never used
} else {
    // *x = 84.0; this will fail, already borrowed below
    println!("{}", r); // 3 // 'a
}
//4 lifetime ends

Listing 1-8

    let mut x = Box::new(42);
    let mut z = &x; // 'a -> 1 lifetime starts
    for i in 0..100 {
        println!("{}", z); // 'a -> 2
        //3 move out of x, which ends the lifetime 'a 
        x = Box::new(i);
        z = &x; // 'a -> 4  restart the lifetime
    }
    println!("{}", z); // 'a

Listing 1-9, “holes in lifetime”

Generic Lifetimes

Lifetime Variance