Lifetime

Lifetime is one of the Rust features that the compiler uses to ensure memory safety. The lifetime specifies the minimum duration an object must live to be used safely. Let's try to do something that is allowed in certain programming languages, but is actually an error to do so:

fn get_element_inc(elements: &[i32], index: usize) -> &i32 {
    let element = elements[index] + 1;
    &element
}

Here, we try to return a reference from a stack-allocated value. The problem is that this value will be deallocated when the function returns and the caller will try to access this deallocated value. In other programming languages, this code will compile fine and produce (hopefully) a segmentation fault at runtime. But Rust is a safe programming language ...

Get Rust Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.