Skip to content
Theory · Lifetimes · lesson 2 of 6

'a in a signature

Inside one function, the compiler sees by itself where each value and each reference lives. It gets harder when a reference comes back from another function. Let's write a function that picks the longer of two strings:

Rust
fn longest(x: &str, y: &str) -> &str { // ✗
    if x.len() >= y.len() { x } else { y }
}

fn main() {
    println!("{}", longest("library", "book"));
}
TEXT
error[E0106]: missing lifetime specifier

The function body is correct; the error is in the signature. The compiler checks each function separately, and at the call site it looks not into the body of longest but only at its header. The header promises to return a reference, but does not say whom it is borrowed from: x or y. And how long the result stays valid depends on that.

In the library picture, the function receives two tickets with different stamps and hands one back. What date goes on that ticket? Until it is written down, the librarian cannot check whoever uses the ticket.

The annotation 'a

A lifetime annotation is a name for a stretch of code, written with an apostrophe: 'a, 'b. You declare it in angle brackets after the function name, like a generic type T, and put it right after &: &'a str.

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

fn main() {
    let a = String::from("library");
    let b = String::from("book");
    println!("{}", longest(&a, &b)); // library
    println!("{}", longest("ok", "yes")); // yes
}

Let's take the signature apart:

  1. <'a> declares the name 'a; an annotation declared this way is called a lifetime parameter, as <T> is called a type parameter.
  2. x: &'a str and y: &'a str say: both references are valid at least on the stretch 'a.
  3. -> &'a str promises: the result is valid on the same stretch 'a.

The call longest(&a, &b) passes references to String where &str is expected: Rust turns a &String into a slice of the whole string by itself. The literals "ok" and "yes" are already &str, and the function returns the longer one, yes.

No longer than the shorter input

Which stretch does the compiler put in place of 'a? It picks it at the call site: the common part of both arguments' stretches, where both x and y are alive. So the returned reference lives no longer than the shortest input. The ticket longest hands back gets the earlier of the two dates.

Step through the program and watch the note on the main frame: it shows up to which line each reference is valid.

LiveThe ticket with the earlier datestep 1 of 8 · frames: 1

a owns the string library and lives until the last } of main.

Watch up to which line each reference is valid

Let's sum up what the example showed:

  1. a lives until the end of main, and b only until the } of the inner block on line 14.
  2. 'a in the call is the common stretch of a and b, that is, until line 14.
  3. r points to a, but by the signature it is valid only until line 14.
  4. r is used on line 13, inside the block, so the program builds.

The compiler does not know which string longest will return: that is decided at run time, by the lengths. So it checks the signature, not the value. The signature says the result may be borrowed from b too, so it may not outlive b, even if it actually points to a.

If the function always returns x, you tie the result to it alone: fn first<'a>(x: &'a str, y: &str) -> &'a str. Then the result is limited by x only, and y may die earlier.

An annotation extends nothing

'a does not make a string live longer. The annotation only describes the link between references, and the value is still freed by the } of its owner's block. If the described link does not hold, the compiler does not fix the program; it refuses to build it. At run time nothing is left of the annotations.

This is where the library picture stops being accurate. In a library, you can arrange for a book to stay in the room a little longer. An annotation cannot do that: it keeps a value alive not one line longer, and the compiler only compares the stretches already in the code.

The longest task is an interview classic. Interviewers usually ask why it does not compile without 'a and what 'a means. The answer:

  • without an annotation, the signature does not say which input the result is borrowed from: error E0106;
  • 'a ties the result to both inputs;
  • the compiler puts the common stretch of the arguments in place of 'a, so the result cannot outlive the shorter of them;
  • an annotation extends nothing and does not exist at run time.

Common mistake

The result of longest is used after the shorter input has been freed:

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

fn main() {
    let a = String::from("library");
    let result;
    {
        let b = String::from("book");
        result = longest(&a, &b); // ✗
    }
    println!("{result}");
}
TEXT
error[E0597]: `b` does not live long enough

At run time result would point to a, which is still alive. But the compiler looks at the signature: the result may be borrowed from b, and b is freed at the block's }, before the print. The same happens if the block is an expression: let result = { let b = …; longest(&a, &b) };. The string b still dies at the }, while the result leaves the block.

The compiler finds the error, and the program never even starts. The fix is to print the result inside the block, or to declare b next to a so that it lives as long.

Key points

  • Without an annotation, fn longest(x: &str, y: &str) -> &str does not compile: error E0106.
  • fn longest<'a>(x: &'a str, y: &'a str) -> &'a str ties the result to both inputs: it lives no longer than the shortest.
  • The compiler checks the signature, not which value actually comes back; a violation is error E0597 at build time.
  • An annotation extends nothing and does not exist at run time.