WeCodeAcademy

Rust Lifetimes

A lifetime tells the compiler how long a reference stays valid. Most of the time Rust works it out, but when a function returns a reference you may need to name it with 'a.

ExampleRust
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

struct Excerpt<'a> {
    part: &'a str,
}

fn main() {
    let first = String::from("a long sentence");
    let result;
    {
        let second = String::from("short");
        result = longest(first.as_str(), second.as_str()).to_string();
    }
    println!("{}", result);

    let text = String::from("Call me Ishmael. Some years ago...");
    let excerpt = Excerpt { part: text.split('.').next().unwrap() };
    println!("{}", excerpt.part);
}
Output
a long sentence
Call me Ishmael

The annotation <'a> says: the returned reference lives no longer than the two inputs. This is how Rust prevents dangling references.

Quick check

What problem do lifetimes prevent?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.