Ownership in Practice · 14 min · free with an account

Lifetime Elision

Lesson preview · about 30%

The common lifetime relationships Rust infers.

Core idea

Rust omits obvious lifetime annotations using a small set of rules.

Start with the idea

Rust omits obvious lifetime annotations using a small set of rules. One borrowed input can usually determine the returned borrow, keeping signatures readable without weakening the proof.

Elision means the compiler fills in common lifetime relationships you did not write. In fn first(text: &str) -> &str, the only borrowed input is text, so the returned slice must be tied to it. The function cannot create a reference that outlives the caller's text. Writing the equivalent named lifetime can be educational, but it does not make the result live longer or change runtime behavior.

The simple rules become less obvious with two borrowed inputs.

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