2

In the Rust documentation they give this example of how structs need lifetimes when they contain references:

struct Foo<'a> {
    x: &'a i32,
}

because

We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.

My question is: shouldn't that be implicit? When would we ever not care about an instance of our struct outliving a reference it contains?

Rust already has lifetime elision rules for functions and methods so that we don't have to explicitly declare lifetime constraints. Why don't they have similar elision rules for structs?

trent
  • 25,033
  • 7
  • 51
  • 90
AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
  • 1
    [This answer](https://stackoverflow.com/a/31625653/3650362) to [Why are explicit lifetimes needed in Rust?](https://stackoverflow.com/q/31609137/3650362) has an example of using the same struct where the lifetime parameter is used by the compiler to forbid an illegal piece of code. – trent Jun 27 '18 at 14:31
  • 1
    Note that you are linking to the documentation for Rust 1.9. Rust 1.27 is the newest version, so that documentation is approximately **2 years old** at this point. – Shepmaster Jun 27 '18 at 14:36
  • When I linked that, claiming it didn't work, in fact it did work because the compiler can now promote the lifetime of references to constants to `'static`. I have updated the example in the answer. – trent Jun 27 '18 at 14:49

0 Answers0