C.W.K.
Stream
Lesson 01 of 05 · published

Why Lifetimes Exist

~11 min · lifetimes, why, concept

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

The borrowing track ended with a promise: the compiler tracks how long each reference is valid, and that tracking is called lifetimes. This track demystifies the scariest-looking syntax in Rust — and shows you it's mostly invisible.

Lifetimes are not durations

First, kill the wrong intuition: a lifetime is not 'how many milliseconds the value lives.' It's a compile-time region of code over which a reference is valid. The compiler reasons about these regions to guarantee no reference ever points at dropped data. You're not timing anything; you're describing relationships between scopes.

Most lifetimes are inferred

Here's the relief: the vast majority of the time you write zero lifetime annotations. You've already written functions taking references without a single 'a in sight. Annotations only appear when the compiler genuinely can't figure out a relationship on its own.

A lifetime describes a relationship, not a duration. Annotations like 'a don't change how long anything lives — they describe which references must stay valid as long as which others. You're giving the compiler a fact it couldn't infer, nothing more.

When you must annotate

The classic case: a function takes two references and returns one. Which input does the output borrow from? The compiler can't always tell, so it asks you to say. That single scenario is where most lifetime syntax comes from — and it's the focus of the next two lessons.

Code

Lifetimes you never had to write·rust
// No lifetime annotation needed — the compiler infers it:
fn first_line(text: &str) -> &str {
    text.lines().next().unwrap_or("")
}

fn main() {
    let doc = String::from("first line\nsecond line");
    let line = first_line(&doc);
    println!("{line}");
    // The compiler already proved `line` can't outlive `doc`.
    // You wrote no 'a — elision handled it.
}

External links

Exercise

Write a function that takes one &str and returns a &str slice of it (say, everything after the first character). Notice you need zero lifetime annotations. Then articulate why: with only one input reference, what does the output obviously borrow from?
Hint
With a single input lifetime, there's no ambiguity — the output can only borrow from that one input, so the compiler infers it. Ambiguity (and annotations) only arise with multiple input references.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.