---
title: "Lifetimes in Rust: how long a reference lives"
slug: "lifetimes"
description: "See how lifetimes tell the compiler how long a reference is valid: longest, structs that hold a reference and elision. Fix a missing lifetime specifier."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/lifetimes"
---

# Lifetimes in Rust: how long a reference lives

How does Rust know a reference is still valid?

## Predict

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

fn main() {
    let first = String::from("lifetime");
    let second = String::from("ref");
    println!("{}", longest(&first, &second));
}
```

What does this program print?

- lifetime
- ref
- It does not compile because the result borrows from two values

Answer: lifetime — Both Strings live in main, and longest returns the longer one: lifetime has 8 letters, ref has 3.

Output:

```
lifetime
```

Both inputs live until the end of `main`, so the returned reference is valid for the whole `println!`.

## Every reference has a lifetime

Every reference has a **lifetime**: the part of the program where it is valid. Most of the time the compiler infers it and you write nothing. This is called lifetime elision. The **borrow checker** compares lifetimes and rejects a reference that would outlive the value it points to. Without that check you would get a dangling reference.

## longest with an inner scope

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

fn main() {
    let outer = String::from("long string");
    {
        let inner = String::from("short");
        let result = longest(&outer, &inner);
        println!("longest is {result}");
    }
    println!("outer is still {outer}");
}
```

Output:

```
longest is long string
outer is still long string
```

`result` is used inside the block, while `outer` and `inner` both still live. Using `result` after the block would not compile, because `inner` is dropped there.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=991bdd08951be94b6e521bb53f9ba606

## What the annotation says

The annotation `'a` does not make anything live longer. It describes a relation: the returned reference is valid for as long as both inputs are. A struct that holds a reference needs a lifetime parameter too: `struct Excerpt<'a>`. The special lifetime `'static` lasts for the whole program. String literals have it.

## A struct that holds a reference

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

impl<'a> Excerpt<'a> {
    fn text(&self) -> &str {
        self.part
    }
}

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

Output:

```
Call me Ishmael
```

`Excerpt<'a>` cannot outlive the `String` `novel`, which owns the text. The `text` method needs no annotation, because elision ties its result to `&self`.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=db962a1098d046a83a2c4c973c5d2677

## Fix it

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

fn main() {
    println!("{}", longest("lifetime", "ref"));
}
```

This program does not compile. What is the bug?

- The compiler cannot tell whether the result borrows from a or from b, so it wants a lifetime annotation
- if and else must return the same variable
- len() cannot be called on &str

Answer: The compiler cannot tell whether the result borrows from a or from b, so it wants a lifetime annotation — Write <'a> and put 'a on both parameters and the result.

Compiler message:

```
error[E0106]: missing lifetime specifier
```

Fixed:

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

fn main() {
    println!("{}", longest("lifetime", "ref"));
}
```

Output:

```
lifetime
```

## Say it back

In your own words: what does the 'a on longest promise?

Our sentence: That the returned reference is valid for as long as both arguments are, so the caller must not use it after either input is gone.

## Mission (10 min)

Write a first_word function that returns a slice of its input, and a struct that holds a &str. Then try returning a reference to a String created inside the function and read the error.

```sh
cargo new lifetimes
cd lifetimes
cargo run
```

## Common questions

### What is a lifetime in Rust?

A lifetime is the span of code where a reference is valid. Every reference has one, and the compiler usually works it out. The borrow checker uses lifetimes to make sure a reference never outlives the value it points to, which prevents dangling references. You only write lifetimes yourself when the compiler cannot tell how references relate.

### Does a lifetime annotation change how long a value lives?

No. An annotation like 'a only describes how the lifetimes of references relate, so the compiler can check them. It does not extend the life of any value. In longest<'a>, it says the result is valid as long as both inputs are. If the code breaks that promise, the compiler reports an error.

### What does 'static mean in Rust?

'static is a lifetime that lasts for the whole run of the program. String literals have it, because their text is stored in the program itself. A type that needs 'static holds no borrowed data that could go away. Do not add it just to silence an error: the error usually points to a real ownership problem.

## Sources

- https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html (read 2026-12-03)
- https://doc.rust-lang.org/reference/lifetime-elision.html (read 2026-12-03)
- https://doc.rust-lang.org/nomicon/lifetimes.html (read 2026-12-03)

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03.
