Rust Abstractions · 19 min · free with an account

Lifetimes

Lesson preview · about 30%

Lifetime annotations connect the borrows in a signature.

Core idea

A struct holding a reference is bounded by that reference's lifetime.

Start with the idea

Elision handles the common shapes, so you write annotations only when the relationship is genuinely ambiguous — typically when several references go in and one comes out. A struct holding a reference needs one too, because the struct cannot outlive what it borrows.

A reference field makes a struct dependent on data owned elsewhere. Excerpt<'a> says its part cannot be used after the borrowed text becomes invalid. The annotation documents and checks a relationship; it does not allocate, copy, or lengthen the source string. If an Excerpt must outlive the source, the model should own a String instead of holding &str.

In the example, part(&self) returns a view of the existing borrowed text.

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