9.7 Structs and Ownership

Ownership plays a crucial role in how structs manage their fields. Some structs take full ownership of their data, while others hold references to external data. Understanding these distinctions is essential for writing safe and efficient Rust programs.

9.7.1 Owned Fields

In most cases, a struct owns its fields. When the struct goes out of scope, Rust automatically drops each field in a safe, predictable order, preventing memory leaks or dangling references:

struct DataHolder {
    data: String,
}

fn main() {
    let holder = DataHolder {
        data: String::from("Some data"),
    };
    // `holder` owns the string "Some data"
} // `holder` and its owned data are dropped here

If a struct needs to reference data owned elsewhere, you must carefully consider lifetimes.

9.7.2 Fields Containing References

When a struct contains references, Rust’s lifetime annotations ensure that the data referenced by the struct remains valid for as long as the struct itself is in use.

Defining Lifetimes

You add lifetime parameters to indicate how long the referenced data must remain valid:

#![allow(unused)]
fn main() {
struct PersonRef<'a> {
    name: &'a str,
    age: u8,
}
}

Using Lifetimes in Practice

struct PersonRef<'a> {
    name: &'a str,
    age: u8,
}

fn main() {
    let name = String::from("Henry");
    let person = PersonRef {
        name: &name,
        age: 50,
    };

    println!("{} is {} years old.", person.name, person.age);
}

Rust ensures that name remains valid for the person struct’s lifetime, preventing dangling references.