Ownership & Borrowing · 16 min · free with an account

Lifetime Intuition

Lesson preview · about 30%

Lifetimes describe relationships between references, not timers.

Core idea

A lifetime annotation relates borrows; it never extends one.

Start with the idea

An annotation does not change how long anything lives. It tells the compiler how input and output borrows are connected, so it can prove a returned reference never outlives the data behind it. Most of the time inference handles this and you write nothing at all.

A lifetime is a relationship the compiler uses to prove a reference is valid when it is used. It is not a timer and an annotation cannot keep memory alive. In longest, both input references are related to the returned reference through 'a. The caller must use the result only while the selected input could still be valid. This is conservative: at compile time the function could return either argument, so the result is limited by the shorter applicable borrow.

Trace a call where one string lives for the whole function and another is created in an inner block.

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 Ownership Mastery