9.9 Structs and Ownership

9.9.1 Ownership of Fields

Structs can own data. When a struct instance goes out of scope, its owned data is dropped.

struct DataHolder {
    data: String,
}

fn main() {
    let holder = DataHolder {
        data: String::from("Some data"),
    };
    // `holder` owns the `String` data
}

9.9.2 Borrowing in Structs

Structs can hold references, but you need to specify lifetimes.

#![allow(unused)]
fn main() {
struct RefHolder<'a> {
    data: &'a str,
}
}
  • Lifetimes ensure that the referenced data outlives the struct instance.