Skip to main content


More Rust stuff

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

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:

struct Foo<'a> {
  bar: &'a String,
  baz: &'a String,
}
struct Foo<'a, 'b> {
  bar: &'a String,
  baz: &'b String,
}

More info on the elision rules is at the Rustonomicon.
in reply to Ryan Frame

@Ryan Frame This makes sense. One would think however that they could infer it if there's only one reference in the struct the say way you don't have to specify a lifetime for methods that only have a &self and return a reference.

This website uses cookies. If you continue browsing this website, you agree to the usage of cookies.