Lifetimes

All variables in Rust code have a lifetime, which is the area of code in which the variable is defined. Suppose we declare a variable n with the binding let n = 42u32; Such a value is valid from where it is declared to when it is no longer referenced; its lifetime ends there. This is illustrated in the following code snippet:

// see code in Chapter 7/code/lifetimes.rs    
fn main() { 
    let n = 42u32; 
    let n2 = n; // a copy of the value from n to n2 
    println!("The value of n2 is {}, the same as n", n2); 
    let p = life(n); 
    println!("p is: {}", p); // p is: 42 
    println!("{}", m);  // error: unresolved name `m`. 
    println!("{}", o);  // error: unresolved name `o`. 
} 
 
fn life(m: u32) -> u32 { 
    let o = m; 
    o 
} 

The lifetime of n ends when the main() function ...

Get Rust Essentials - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.