Lifetimes in structs
A struct that holds a reference needs a lifetime parameter. It is a declaration that instances of the struct cannot outlive the data they borrow.
This is how zero-copy parsers work: a `Parser<'a>` holds `&'a str` slices into the original input instead of allocating a new `String` for every token.
If keeping that relationship straight starts to hurt, that is usually a hint that the struct should own its data instead — `String` rather than `&str`. Borrowing is an optimisation, not an obligation.
A struct that outlives its data
struct Holder<'a> { text: &'a str }
fn main() {
let holder;
{
let temporary = String::from("gone soon");
holder = Holder { text: &temporary }; // error[E0597]
}
println!("{}", holder.text);
}error[E0597]: `temporary` does not live long enough
Either keep the borrowed data alive as long as the struct, or store an owned `String` in the field so the struct does not depend on anyone else.
Run it and change it
The editor below is live: edit anything and the real compiler output updates by itself.