Skip to Content
Rust Programming By Example
book

Rust Programming By Example

by Guillaume Gomez, Antoni Boucher
January 2018
Beginner to intermediate
454 pages
10h 8m
English
Packt Publishing
Content preview from Rust Programming By Example

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust Programming Cookbook

Rust Programming Cookbook

Claus Matzinger
Rust Web Programming

Rust Web Programming

Maxwell Flitton

Publisher Resources

ISBN: 9781788390637Supplemental Content