Lifetimes

Lifetimes in Rust: Contractors put a sign at the road: "Site office -- second gate on the left." It is useful precisely because it does not contain an office.

The Analogy: The Temporary Sign And The Site Office

Contractors put a sign at the road: "Site office -- second gate on the left." It is useful precisely because it does not contain an office. It points at one. Everything a reference does in a Rust program, that sign does at the roadside: it is small, it is cheap to copy, and its whole value is that somebody else is holding the actual thing.

There is exactly one way for the sign to go wrong, and it has nothing to do with the wording. The office closes, the portacabin is towed off on a lorry, and the sign is still standing there sending visitors through a gate at an empty patch of gravel. Nothing about the sign changed. What changed is that the thing it pointed at stopped existing, and there is no way to tell that by reading the sign.

So the site rules carry a clause: any sign pointing at the office comes down no later than the day the office does. Be careful about what that clause is. It does not keep the office open one extra hour. It is not a lease and it buys no time. It is a written statement of the relationship between two durations, put there so an inspector can approve the site by reading the paperwork instead of following every visitor around for a month. Lifetime annotations are that clause, and the compiler is that inspector.

Most signs never need the clause spelled out, because there is one office and the standing convention already covers it -- everyone knows what "the office" refers to. The clause has to be written down at precisely the moment the convention runs out: two offices on the site, a sign that says only "the office", and no way for the inspector to work out which closure it is tied to. And one kind of sign is exempt from all of this: the one pointing at the town hall, which stood before the site existed and will still be there after it is gone.


Syntax or Core Structure

A lifetime parameter is declared in angle brackets like a type parameter, written with a leading apostrophe, and then used on the references it relates:

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

fn main() {
    let north = String::from("north gate");
    let east = String::from("east");

    println!("{}", longest(&north, &east));
    println!("{}", longest("alpha", "bravo-two"));

    let picked;

    {
        let inner = String::from("a much longer name");
        picked = longest(&north, &inner).len();
    }

    println!("len {}", picked);
}

Output:

north gate
bravo-two
len 18

The signature reads: for some region 'a, given two string references both valid throughout 'a, the result is a reference valid throughout 'a. In practice the compiler picks the shortest region that satisfies that at each call, so the result may not be used after either input has gone. The third call shows both halves of the rule at once -- longest(&north, &inner) is perfectly usable inside the block, and the .len() happens there, so what leaves the block is a usize and not a reference.

Try to smuggle the reference itself out and the compiler stops you. Try instead to write a function that builds a String locally and returns &owned under a -> &'a str signature, and it stops you again with E0515, cannot return reference to local variable. That second refusal is the important one, because it shows what the annotation is not. Writing 'a on the return type never extends anything's life; the local is still dropped at the closing brace, and all the annotation did was let the compiler notice.

Most references need no annotation at all, because three elision rules cover the common shapes:

RuleWhat the compiler doesResult
1Gives every elided input reference its own fresh lifetimefn f(a: &str, b: &str) gets two, unrelated
2If there is exactly one input lifetime, the output takes itfn f(a: &str) -> &str needs nothing written
3If an input is &self or &mut self, the output takes self'sfn name(&self) -> &str needs nothing written

The rules are applied in order and they either settle the output lifetime or they do not. When they do not -- two input references and a returned reference, with no self in sight -- the error is E0106, missing lifetime specifier, and it is the compiler saying it cannot guess which input the result points into.


Technical Depth: Which Input Does The Result Point Into

Elision at work, and the tighter signature it hides

One input reference means rule 2 settles everything:

fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(i) => &text[..i],
        None => text,
    }
}

fn main() {
    println!("[{}]", first_word("north gate open"));
    println!("[{}]", first_word("solo"));
}

Output:

[north]
[solo]

Now add a second reference that the result does not borrow from. The lazy fix is to give both parameters 'a and move on. The correct fix is to annotate only the one the output actually comes from:

fn prefix<'a>(text: &'a str, sep: &str) -> &'a str {
    match text.find(sep) {
        Some(i) => &text[..i],
        None => text,
    }
}

fn main() {
    let text = String::from("west-gate-3");
    let head;

    {
        let sep = String::from("-");
        head = prefix(&text, &sep);
    }

    println!("{head}");
}

Output:

west

sep is dead by the time head is printed, and that is fine, because the signature never claimed the result had anything to do with sep. Change the signature to fn prefix<'a>(text: &'a str, sep: &'a str) -> &'a str and this exact main stops compiling: 'a would then have to cover both inputs and the result, which forces it to end when sep does. The annotation is part of the API, and a needlessly shared lifetime turns away callers for no reason.

Structs that hold references

A struct containing a reference must declare the relationship too, and the meaning is the same clause: this value may not outlive what it points into.

struct Excerpt<'a> {
    source: &'a str,
    from: usize,
    to: usize,
}

impl<'a> Excerpt<'a> {
    fn new(source: &'a str, from: usize, to: usize) -> Excerpt<'a> {
        Excerpt { source, from, to }
    }

    fn text(&self) -> &str {
        &self.source[self.from..self.to]
    }

    fn width(&self) -> usize {
        self.to - self.from
    }
}

fn main() {
    let log = String::from("2026-09-04 WARN disk at 94 percent");
    let level = Excerpt::new(&log, 11, 15);
    let subject = Excerpt::new(&log, 16, 20);

    println!("level   [{}] width {}", level.text(), level.width());
    println!("subject [{}] width {}", subject.text(), subject.width());
}

Output:

level   [WARN] width 4
subject [disk] width 4

impl<'a> Excerpt<'a> declares the lifetime and then uses it, exactly as impl<T> Pair<T> declared and used a type parameter. Inside, text needs no annotation: &self is present, so rule 3 ties the result to the borrow of self. That is convenient here and it is a trap in the next section.

'static, and what it does not mean

fn main() {
    let banner: &'static str = "CodeAcademix";
    let owned = String::from("runtime value");
    let borrowed: &str = &owned;

    println!("{} / {}", banner, borrowed);
    println!("{} {}", banner.len(), borrowed.len());
}

Output:

CodeAcademix / runtime value
12 13

String literals live in the compiled binary, so a reference to one is valid for the whole run and its type is &'static str. That much is straightforward. The confusion comes from the other use of the same word: T: 'static as a bound does not say "this value lives for the whole program". It says "this type contains no references that could go stale", which every owned type satisfies -- String: 'static holds, and a String created and dropped inside one function still satisfies it. The bound is about what a type could point at, not about how long a particular value happens to live.

Lifetimes and type parameters in the same list

They share the angle brackets, lifetimes first, and they are different kinds of thing: one is a bound on capability, the other a statement about duration.

use std::fmt::Display;

fn announce<'a, T: Display>(items: &'a [T], label: &str) -> &'a T {
    println!("{} has {} items", label, items.len());

    &items[0]
}

fn main() {
    let ports = [443, 22, 80];
    let names = [String::from("north"), String::from("south")];

    println!("first {}", announce(&ports, "ports"));
    println!("first {}", announce(&names, "names"));
}

Output:

ports has 3 items
first 443
names has 2 items
first north

The interleaved output is not a mistake: the argument to println! is evaluated before the macro prints anything, so announce runs and prints its own line first. label gets its own elided lifetime by rule 1 and is deliberately left unannotated, because the result does not point into it -- the same discipline as prefix, applied to a generic function.


Real World Example: A Config Parser That Borrows Instead Of Copying

A settings file is read once into a String. Every key and every value already exists inside that text, so copying them into fresh Strings would allocate once per setting for no reason. Lifetimes are what make the alternative safe: the parser hands back slices pointing into the original text, and the compiler guarantees the text outlives them.

struct Setting<'a> {
    key: &'a str,
    value: &'a str,
    line: usize,
}

struct Config<'a> {
    source: &'a str,
    settings: Vec<Setting<'a>>,
    problems: Vec<String>,
}

impl<'a> Config<'a> {
    fn parse(source: &'a str) -> Config<'a> {
        let mut settings = Vec::new();
        let mut problems = Vec::new();

        for (i, raw) in source.lines().enumerate() {
            let line = i + 1;
            let text = raw.trim();

            if text.is_empty() || text.starts_with('#') {
                continue;
            }

            match text.find('=') {
                Some(at) => {
                    let key = text[..at].trim();
                    let value = text[at + 1..].trim();

                    if key.is_empty() {
                        problems.push(format!("line {line}: empty key"));
                    } else {
                        settings.push(Setting { key, value, line });
                    }
                }
                None => problems.push(format!("line {line}: no '=' in {text:?}")),
            }
        }

        Config { source, settings, problems }
    }

    fn get(&self, key: &str) -> Option<&'a str> {
        for s in &self.settings {
            if s.key == key {
                return Some(s.value);
            }
        }

        None
    }

    fn where_set(&self, key: &str) -> Option<usize> {
        for s in &self.settings {
            if s.key == key {
                return Some(s.line);
            }
        }

        None
    }

    fn bytes(&self) -> usize {
        self.source.len()
    }
}

fn main() {
    let file = concat!(
        "# gateway settings\n",
        "host = 10.0.0.4\n",
        "port=8080\n",
        "\n",
        "  timeout = 30\n",
        "= 5\n",
        "retries\n",
        "name = north gate\n"
    );

    let config = Config::parse(file);

    println!(
        "{} bytes, {} settings, {} problems",
        config.bytes(),
        config.settings.len(),
        config.problems.len()
    );

    for key in ["host", "port", "name", "missing"] {
        match config.get(key) {
            Some(v) => println!("  {:<8} {:?} (line {})", key, v, config.where_set(key).unwrap()),
            None => println!("  {:<8} not set", key),
        }
    }

    for p in &config.problems {
        println!("  ! {p}");
    }

    let saved;

    {
        let temporary = Config::parse(file);
        saved = temporary.get("timeout");
    }

    println!("saved {:?}", saved);
}

Output:

91 bytes, 4 settings, 2 problems
  host     "10.0.0.4" (line 2)
  port     "8080" (line 3)
  name     "north gate" (line 8)
  missing  not set
  ! line 6: empty key
  ! line 7: no '=' in "retries"
saved Some("30")

Count the allocations. There is one Vec of settings, one Vec of problem strings, and one String per problem -- and nothing at all for the keys and values, which are slices into the 91 bytes that were already in memory. The <'a> threaded through Setting, Config and parse is the entire cost of that, and it buys a guarantee: no Config and no Setting can outlive the text it points into, checked once at compile time and never again at run time.

The block at the end of main is the reason get returns Option<&'a str> and not Option<&str>. Elision rule 3 would have seen &self and tied the result to the borrow of the Config, which would make the returned value die with the parser. The explicit 'a says something different and truer: the value borrows the source, so it survives temporary being dropped, and saved is still printable afterwards. One lifetime name, two materially different APIs, and no difference in the generated code.

Notice what is not borrowed. problems holds owned Strings, because those messages are constructed rather than found -- line 6: empty key contains a line number that appears nowhere in the file, so there is nothing to point at. That mix is the normal outcome and worth being deliberate about: borrow what the input already contains, own what you compute.

The limits are mostly about scale and about typing. get is a linear scan, and main scans twice for every key -- once for the value and once for the line -- which is fine for a few dozen settings and wrong for a few thousand, where a HashMap<&str, Setting> built during the parse would be the fix. A duplicate key is not reported at all; the first occurrence wins silently. Values are raw text with no types, so port is the string "8080" and any caller wanting a number has to parse it and handle the failure. Quoting, escapes, multi-line values and [section] headers are all unsupported, and an inline # is treated as part of the value rather than a comment. And the borrowing itself has a cost worth stating plainly: the whole file must be read into memory and kept alive for as long as the config is used, so this design cannot parse from a streaming reader -- if that is a requirement, Setting has to own its strings and the lifetime parameter goes away.


Common Mistakes

  1. Believing an annotation extends a lifetime. A function that builds a String locally and returns &owned fails with E0515 no matter what lifetime is written on the return type. The local is dropped at the closing brace and the annotation only ever describes; it never grants. If the value must survive the call, return the String itself.
  1. Sharing one lifetime across parameters that are unrelated. fn prefix<'a>(text: &'a str, sep: &'a str) -> &'a str compiles and quietly forces 'a to end when the shorter argument does, so callers holding the result past a short-lived separator are rejected for no reason. Annotate only the input the result actually points into.
  1. Adding lifetimes by trial and error until it compiles. A signature that compiles is not necessarily the signature you meant, and the wrong one is a permanent restriction on every caller. Work out which input the returned reference comes from and write that; if the answer is "neither, it is computed", the return type should be owned.
  1. Reading T: 'static as "lives for the whole program". It means the type contains no references that could go stale, which every owned type satisfies. String: 'static is true, and a String created and dropped inside one function satisfies the bound perfectly well.
  1. Letting rule 3 tie a result to &self when the caller needs it to outlive the struct. fn get(&self, k: &str) -> Option<&str> on a borrowing parser returns something that dies with the parser. Write the struct's own lifetime -- Option<&'a str> -- when the value comes from the borrowed source rather than from the struct.
  1. Reaching for 'static to silence E0106. It is the loudest possible over-constraint: it accepts literals and leaked memory and nothing else. The error is asking which input the output borrows from, and 'static answers "none of them", which is almost never true.
  1. Putting a reference in a struct to save an allocation, then fighting the consequences. A struct with a lifetime parameter cannot outlive its borrow, cannot easily be returned upward, and cannot be stored in a long-lived collection alongside the data it points at. Sometimes owning the data is the correct design and not a defeat.
  1. Assuming a lifetime name means something across signatures. The 'a in one function has no relationship to the 'a in another; they are local parameter names like T. Only the annotations within a single signature or a single impl block relate to each other.
  1. Trying to build a struct that holds a String and a &str into that same String. This is the self-referential struct, and no lifetime annotation expresses it, because the reference would have to be valid before the struct exists. Store indices instead, as Excerpt does, or keep the owner and the view in separate values.

Best Practices

  • Write nothing first. Let elision handle the signature and add annotations only when the compiler asks with E0106, which names the parameters it is choosing between.
  • Give the output the lifetime of the one input it actually borrows from, and leave every other reference parameter elided. The tighter signature accepts strictly more callers.
  • Be explicit on methods whose result should outlive &self. Rule 3 is convenient and silently wrong for any type that borrows its data from elsewhere.
  • Borrow what the input already contains and own what you compute. A struct mixing &'a str fields with String fields is usually a sign the design is right, not confused.
  • When a lifetime is genuinely fighting you across several layers of a program, price the alternative honestly: an owned String costs one allocation and removes an entire lifetime parameter from every signature that mentions the type.
  • Keep the lifetime parameter visible in the constructor -- fn new(source: &'a str) -> Excerpt<'a> -- so a caller can see the tie without reading the struct definition.
  • Reserve 'static for literals, constants and data genuinely baked into the binary. Use it as a bound when you mean "no borrowed contents", and say which of the two meanings you intend in a comment if the context is at all unclear.
  • Prefer indices into a source over a second reference when a type needs to describe part of something it does not own; they are Copy, they need no lifetime, and they can be serialised.

Practice Exercises

  1. Change Config::get to return Option<&str> and record the exact error the saved block now produces. Explain which elision rule chose that lifetime, then restore the annotation and describe in one sentence what the caller gained.
  1. Add [section] header support: give Setting a section: Option<&'a str> field, track the current section while parsing, and make get take an optional section to match. Verify that no new allocation is introduced -- the section names must be slices of the source too.
  1. Write a function fn between<'a>(text: &'a str, open: &str, close: &str) -> Option<&'a str> returning what lies between the first open and the next close after it. Then write a caller in which both delimiters are short-lived Strings and the result is used after they are dropped, and confirm it compiles -- that is the proof your annotations are as loose as they should be.
  1. Convert Setting to own its key and value as Strings. Count how many allocations the sample file now costs, list every signature that lost a lifetime parameter, then state which of the two versions you would ship for a program that reads one config at startup and holds it forever -- and why.