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,
};
A lifetime is a rule that tells Rust how long a reference to data is safe to use. You use them when a struct holds a reference to data owned by something else, ensuring the struct doesn't try to access data that has already been deleted. Think of it like a library book card that expires; the card (struct) is only valid as long as the book (data) is still on the shelf.