Course contentsShow
← Rust
Lesson 110 of 1,9102. The Ownership ModelFree lesson

Lifetime Bounds on Struct Fields

Design composite data structures that maintain strict coherence with external data sources.

In this lesson, you will learn how to design structs that safely "borrow" data from the outside world without taking full ownership of it.

The Problem: Owning vs. Referencing

So far, you’ve learned that structs usually own their data. If you have a struct User { name: String }, the struct is responsible for freeing that memory. However, what if you want a struct to simply point to data that exists somewhere else?

If your struct contains a reference (like &str), Rust needs to ensure that the data being pointed to lives at least as long as the struct itself. If the struct outlived the data, you would end up with a dangling reference, causing a memory safety error.

Introducing Lifetime Annotations

When a struct holds a reference, you must add an explicit lifetime annotation to the struct definition. This tells the compiler: "This struct cannot outlive the data it points to."

Look at this example:

struct Book<'a> {
    title: &'a str,
}

fn main() {
    let title_string = String::from("Rust Programming");
    let book = Book { title: &title_string };
    
    // The struct 'book' is now bound to the lifetime of 'title_string'
}

Here, the 'a is a generic lifetime parameter. By adding it, you are creating a "lifetime bound." You are telling the compiler that the Book struct is tied to the scope of whatever &str it holds. If you tried to create a Book from a string that was about to be dropped, the compiler would stop you immediately.

Why this matters

This pattern allows for strict coherence. By forcing you to declare these bounds, Rust ensures that your struct doesn't hold onto a reference that has already been cleaned up by the memory allocator. You are essentially creating a formal contract: as long as an instance of your struct exists, the source of its data is guaranteed to exist as well. This prevents crashes and memory corruption while keeping your data structures lean and efficient.

Key Takeaway: When a struct contains a reference, you must use a generic lifetime annotation to guarantee that the struct never outlives the data it points to.