How to Use Lifetimes in Struct Definitions

Use lifetime parameters in struct definitions to ensure referenced data outlives the struct holding it.

You use lifetimes in struct definitions by annotating reference fields with a lifetime parameter to tell the compiler how long the struct can outlive the data it references.

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

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