How to Use Structs with Lifetimes in Rust

Add lifetime parameters to structs holding references to ensure the struct does not outlive the data it points to.

Add a lifetime parameter to the struct definition and its fields to tell the compiler how long the references inside the struct are valid. This ensures the struct does not outlive the data it references.

struct ImportantExcerpt<'a> {
    part: &'a str,
}

let novel = String::from("Call me Ishmael.");
let first_sentence = novel.split('.').next().unwrap();
let excerpt = ImportantExcerpt {
    part: first_sentence,
};