Core Rust Questions · 16 min · free with an account

Lifetime Reasoning

Lesson preview · about 30%

Lifetimes are about relationships, and saying so is the answer.

Core idea

A lifetime constrains borrows; it never keeps anything alive.

Start with the idea

The common misconception is that a lifetime controls how long a value lives. It does not: it is a compile-time claim about which borrows outlive which. Annotations appear only where inference cannot decide, which is why most code has none.

A lifetime annotation relates references; it does not keep a value alive by itself. Consider a function returning one of two borrowed strings. The output reference must not outlive the input it came from. When the compiler cannot infer which input supplies the result, an annotation such as 'a names their relationship. At the call site, the borrow remains valid only while the underlying owner lives. No annotation can turn a reference to a local temporary into a valid long-lived return value.

Explain this with a failed example: create a String inside a function and return &str pointing into it.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep