Lifetimes

Telling the compiler how long references live when it cannot work it out by itself.

Every reference has a lifetime: the region of code where it is valid. Usually the compiler infers them. When a function returns a reference derived from several inputs, you must say which inputs the result may borrow from — with lifetime parameters like 'a.

Adding lifetime annotations

fn longer<'a>(a: &'a str, b: &'a str) -> &'a str: the result is valid only while both inputs are.

Inside the inner block both strings are alive, so using result there is fine.

struct Token<'a> holds a &'a str, so a Token can never outlive the text it points into.

fn first<'a>(v: &'a Vec<String>) -> &'static str { &v[0] } fn first<'a>(v: &'a Vec<String>) -> &'a str { &v[0] }

The result borrows from v, so it cannot be 'static. Tie the output lifetime to the input it comes from.

When must you write lifetime annotations on a function?

When it returns a reference and the compiler cannot tell which input it comes from — typically several reference parameters and no &self.

What does 'static mean?

The reference is valid for the entire run of the program, like a string literal stored in the binary.