Full Byte Developer.

Rust lifetimes in plain words

Lifetimes name how long references stay valid; annotations tell the borrow checker how parameters and returns relate.

Published here , updated · 3 sources

Lifetimes are how Rust names "this reference stays valid for this scope" so the borrow checker can refuse dangling pointers before you run the binary [1]. Most of the time the compiler infers them; you write 'a when relationships between several references need an explicit name [1]. Pair with stack vs heap memory when placement matters.

Compile a dangling borrow in under a minute

Save a program that lets a reference outlive its data. rustc should refuse it [1]:

dangle.rs
fn main() {
    let r;
    {
        let x = String::from("hello");
        r = &x;
    }
    println!("{}", r);
}
bash
rustc dangle.rs 2>&1 | head -12

Captured output (rustc 1.83.0):

text
error[E0597]: `x` does not live long enough
 --> dangle.rs:5:13
  |
4 |         let x = String::from("hello");
  |             - binding `x` declared here
5 |         r = &x;
  |             ^^ borrowed value does not live long enough
6 |     }
  |     - `x` dropped here while still borrowed
7 |     println!("{}", r);
  |                    - borrow later used here

The Book states the main aim of lifetimes: stop dangling references [1]. Fix by keeping the String alive as long as r, not by hoping the bytes stick around after drop.

Draw valid versus dangling scopes

OK: data outlives borrow let data = String... let r = &data; use r drop data last BAD: inner scope too short { let x = ...; r = &x } use r after } E0597: x dropped Lifetime annotations name relationships for the checker. They do not extend how long values actually live [1].

Ownership decides where values live; lifetimes are the checker language for references tied to those values.

Annotate a return that borrows inputs

When a function returns a reference tied to inputs, Rust may ask for a named lifetime such as 'a [1]. The classic longest sketch from the Book [1]:

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

fn main() {
    let s1 = String::from("long string");
    let s2 = "short";
    println!("{}", longest(s1.as_str(), s2));
}
bash
rustc lifetime_demo.rs && ./lifetime_demo

Captured output:

text
long string

That signature says the returned borrow is valid only while both inputs are; in practice the result lives as long as the shorter input lifetime [1]. Annotations do not change how long values actually live; they constrain which calls the checker accepts [1]. Syntax: lifetime names start with ' and sit after &, as in &'a str [1].

When you need explicit names

Structs that store references need lifetime parameters on the struct so the checker knows the struct cannot outlive the borrowed data [1]:

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

Owned fields (String) avoid the annotation on the struct because the data moves with the value.

Multiple reference parameters with unclear ties need names so the compiler knows which input the return borrows from [1]:

rust
fn pick_first<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
    x
}

Return type 'a forbids returning y when lifetimes differ [1]. Errors that mention a lifetime mismatch usually want this split.

Elision keeps simple APIs quiet

Functions with one reference parameter and one reference return often omit lifetimes; the compiler ties the return to that input [1]. Writing fn foo(s: &str) -> &str is enough on paper because elision fills in 'a. Adding more references or returning references from structs breaks elision and forces explicit names. rustc error text often links the elision chapter when it applies [1].

Static lifetime without cargo-culting it

&'static str means the borrow lasts the whole program (string literals, leaked boxes) [1]. Do not slap 'static on parameters to silence errors unless the API truly requires forever data. A temporary that only needs to outlive a function call does not become 'static because you typed the word [1].

Lifetimes versus moves

Moving a value invalidates borrows of that value. Lifetimes do not override move semantics. &mut and & rules still cap how many live references you may hold [1]. Owned return types (String, Vec) sidestep many lifetime annotations because the caller owns the result. Libraries often prefer owned returns in public APIs unless zero-copy is the point.

Collecting references into a Vec<&str> from a loop requires the source data to live outside the loop scope. Prefer collecting owned String values when building vectors for later use [1].

Read the explain text for E0597

bash
rustc --explain E0597 | head -8

Captured opening lines:

text
This error occurs because a value was dropped while it was still borrowed.

Erroneous code example:

The explain text restates the same scope story: borrowed value dropped while the borrow is still active [1]. Variant errors such as E0515 (cannot return reference to a temporary) point at the same fix: widen owned data or narrow the borrow scope [1]. Read the span labels rustc prints; they mark which binding died too early.

Connection to language tradeoffs

Ownership and borrowing decide who may use a value; lifetimes are the scope language the checker uses for references [1]. Stack versus heap placement still matters for what gets moved (stack vs heap memory). When someone asks whether Rust is "worth the lifetimes," compare wall time and memory claims carefully with Is Go slower than Rust instead of treating compile errors as a speed metric.

Temporary returns and owned escapes

A common compile failure is returning &str that points at a local String created inside the function. The local drops at the closing brace, so the reference would dangle [1]. Two clean escapes: return an owned String, or take an input borrow and return a slice of that input (with a lifetime tying them together). Temporary values in the return expression hit the same wall; rustc's E0515 callout is the cousin of E0597 [1].

Iterator adapters that borrow from a local buffer per iteration fail for the same scope reason. Collect owned data when the vector must outlive the loop that filled it [1].

Higher-ranked bounds (pointer only)

Some traits tie returned borrows to input lifetimes inside impl Trait bounds. You meet them in iterators and async before you memorize the syntax. When the compiler mentions that a lifetime may not live long enough inside a trait impl, return to the Book lifetime chapter and the elision rules rather than guessing 'static [1].

Teaching from the error spans

rustc prints underlines that mark which binding died and where the borrow was later used. Read those spans before you rewrite the whole function. Often the fix is moving a let up one block, not inventing a new abstraction. Clippy sometimes suggests owned returns when lifetimes get noisy; that suggestion is a design hint, not a law [1].

When you explain lifetimes to a teammate, start with the dangling dangle.rs program, then show longest, then show a struct with a borrowed field. That order matches how the Book introduces the topic [1]. Jumping straight to HRTB confuses people who still think 'a extends memory.

Mistakes that waste an afternoon

Adding 'static everywhere to quiet the compiler. You hide real scope bugs [1].

Treating lifetime syntax as a way to extend how long values live. It only states relationships for the checker [1].

Returning a reference to a local String without tying it to an input lifetime. The function body ends; locals drop [1].

Fighting the borrow checker with unsafe to skip lifetime errors in safe-looking APIs. Fix the API shape or ownership first.

Storing references in structs without lifetime parameters on the struct, then wondering why later methods fail to compile [1].

Collecting &str from per-iteration locals into a Vec that outlives the loop. The same E0597 story appears with extra iterators [1].

Copying a lifetime annotation from a blog post into an API where all inputs should be owned. You add noise without gaining zero-copy benefits [1].

What you have now

Book-sourced lifetime intent, an E0597 capture, and a compiling longest example. When rustc asks for 'a, name the relationship between inputs and returns; do not invent forever scopes [1]. Keep stack vs heap memory nearby when someone confuses placement with borrow duration, and use Is Go slower than Rust when the question is about runtime tradeoffs rather than compile-time checks.

Browse the Dev explainers topic.

Send this to the friend who treats lifetime errors as a personal insult.

Dark cube with a cyan-glowing top edge emitting three dashed cyan and orange particle trails toward two horizontal teal beams wrapped in glowing orange rings on a dark grid floor.
References travel only as far as their data stays alive; dashed trails that outlive the source are the dangling case rustc rejects.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

What problem do lifetimes solve?

The Rust Book: every reference has a lifetime (the scope it is valid). The aim is to prevent dangling references.

Do I annotate every reference?

No. Most lifetimes are inferred. Annotate when the compiler cannot tell how multiple references relate, such as a function returning a borrow from one of several inputs.

Does 'a change how long data lives?

No. Lifetime annotations describe relationships for the checker; they do not extend or shrink the real scopes of values.

What is elision?

Rules that let the compiler pick default lifetimes on single-input references so simple functions need no 'a syntax.

Where should I go next?

Read stack vs heap memory for where values live, then is Go slower than Rust for the language tradeoff without lifetime syntax.

Sources

Next in this stack