Lifetimes in Structs
Borrowed fields.
Structs Can Borrow
Most structs own their data. But a struct can also hold a reference to data it does not own. When it does, the struct needs a lifetime parameter.
This guarantees the struct never outlives the borrowed data.
Declaring a Lifetime on a Struct
Add the lifetime in angle brackets after the struct name, then use it on the reference field. This says the struct cannot outlive that reference.
struct Excerpt<'a> {
text: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first = novel.split('.').next().unwrap();
let e = Excerpt { text: first };
println!("{}", e.text);
}All lessons in this course
- Why Lifetimes
- Lifetime Annotations
- Lifetimes in Structs
- Elision Rules