Rust Lifetimes Without the Fear: They're Just Expiry Dates

Rust lifetimes have a reputation, like the haunted house at the end of the street. Inside, it's just a milk carton with an expiry date. Learn what 'a means, why the compiler asks for it, and when to just return a String.

Ada Brackett

5 min read

Every street has one. The haunted house. The one the kids dare each other to touch. In Rust, that house is called lifetimes, and people talk about it in whispers. "Did you hear? Kevin wrote 'a and was never seen again."

Last time I promised you snacks. Here they are: 馃崻. Now let's walk up to the door.

[Cut to a group of kids on bikes outside a creaky house. One kid finally opens the door. Inside is a perfectly normal kitchen, and on the table, a single carton of milk with an expiry date on it. "That's it?" says the kid. The milk does not respond. It is milk.]

That's it. Rust lifetimes are expiry dates for references. A reference must never outlive the thing it points to, and a lifetime is how Rust writes down "good until...".

You've been using them all along

Remember lending the car, back in the ownership post? A borrow (&T) is a reference to something somebody else owns. Rust checks that every reference is gone before the owner throws the value away. Nearly always it works that out on its own, silently, and you never see a lifetime at all. You only meet them when the compiler can't tell which expiry date applies.

The classic: longest

Bash
cargo new lifetimes
cd lifetimes

Try this function:

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

The compiler says no:

error[E0106]: missing lifetime specifier

It isn't being difficult. Think about it: the function returns a reference, but a reference to which input? a might expire tomorrow and b next year. The caller needs to know how long the result is good for, and from this signature, nobody can tell.

So we write the expiry date down:

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

Read 'a out loud as "some stretch of time". The signature now says: "Give me two references that are both good for at least 'a, and I'll give you back one that's good for 'a too." In practice, 'a ends up as the shorter of the two inputs' lifetimes. The result is only as fresh as the older milk.

Notice what lifetimes don't do: they don't make anything live longer. They're labels, not a fridge. They describe how long things already live, so the compiler can check your promises.

Watch it catch a real bug

Rust
fn main() {
    let result;
    {
        let b = String::from("short");
        result = longest("a much longer string", &b);
    }
    println!("{result}");
}
error[E0597]: `b` does not live long enough

b is thrown away at the closing brace, but result might be pointing at it, and we use result afterwards. In C, this compiles, runs, and prints whatever happens to be in that memory now. Maybe your string. Maybe garbage. Maybe, on a bad day, someone's password. Rust catches it before it ever runs.

"But the longer string is the literal, so it would've been fine!" Yes, this time. The signature promises the result could be either input, and Rust checks the promise, not your luck.

Why you rarely write them: elision

If lifetimes were needed everywhere, Rust would be unbearable. So the compiler fills them in with three simple rules, called elision. The one that covers most code: if a function takes exactly one reference, the output borrows from that one.

Rust
fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}

No 'a needed. One input, one possible source, so the compiler writes the expiry date itself. Methods that take &self get a similar rule: by default, the output borrows from self.

Structs that hold references

A struct holding a reference needs a label too, because the struct can't outlive what it points at:

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

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first = novel.split('.').next().unwrap_or("");
    let quote = Excerpt { part: first };
    println!("{}", quote.part);
}

Excerpt<'a> reads as: "this excerpt is good for as long as the text it quotes." If you drop novel while quote is still around, the compiler stops you.

'static: the milk that never expires

'static means "good for the whole run of the program". String literals like "hello" are &'static str, because they're baked into the binary itself. You'll see 'static in error messages and thread APIs. When a compiler hint suggests adding 'static just to make an error go away, be suspicious. It's usually saying "make this live forever", which is rarely what you actually meant.

The escape hatch: return owned data

When the lifetimes start to tangle, there's an honourable way out: stop returning references.

Rust
fn longest_owned(a: &str, b: &str) -> String {
    if a.len() >= b.len() { a.to_string() } else { b.to_string() }
}

A String belongs to whoever receives it, so it has no expiry date to track. It costs a copy. For most code that's nothing. Reach for references when you're sure, and for owned values when you're not. Nobody will take away your Rust card.

Homework

  • Write fn shortest<'a>(a: &'a str, b: &'a str) -> &'a str, then explain to a rubber duck why it needs 'a.
  • Add a method fn part(&self) -> &str to Excerpt and notice it needs no lifetime written out. Elision did it.
  • Chapter 10.3 of the Rust Book, "Validating References with Lifetimes", is free at doc.rust-lang.org/book.

The haunted house was a kitchen the whole time. Eat your cookie. 馃崻