Something that's been bothering me about lifetimes.
When I got to this section in the book, I couldn't (and still can't) understand why it's necessary to specify lifetimes for the references a struct
holds. I mean, if I have:
struct Foo<'a> {
bar: &'a String,
}
Shouldn't it just be assumed that the data referenced by Foo::bar
should have to live at least as long as the Foo
object itself? Why does this have to be explicitly stated? Is there some scenario where you would want this to not be the case?
Edit: formatting fix
Adam Hunt likes this.
Ryan Frame
in reply to Jonathan Lamothe • • •Lifetime elision only applies on function signatures. It might be because no one has done the work? Though I think it's nice to be explicit that the struct holds a reference to something.
Explicit lifetimes would be necessary for a struct with multiple references (or I guess a rule that says they're either all the same or all unique). These are not the same:
More info on the elision rules is at the Rustonomicon.
Lifetime Elision - The Rustonomicon
doc.rust-lang.orgJonathan Lamothe likes this.
Jonathan Lamothe
in reply to Ryan Frame • •&self
and return a reference.