I don't able to understand lifetime specifiers :(

Since this got brought back up and the thread kind of diverged from the point:

The TLDR of struct lifetime annotations is you don't need them until you know exactly why you need them.

Same classic examples are:

If you're writing a parser and you want to be able to return data referencing the input rather than copying it:

fn parse<'input>(input: 'input) -> Result<Value<'input>>

Now the caller knows it can't drop input before the result.

If you have a lockable resource, and you represent that being locked with a type holding a reference into the value:

impl Foo {
  fn lock<'a>(&'a self) -> Lock<'a>;

Now you can reach directly into the locked resource while the result value exists without trouble, because you know that it still exists because the Foo it came from still exists.

There's lots of these really clear uses of lifetime parameters in transient, especially return, values. If you don't have one, don't use them.

If the question is really "why do they need to be explicit in structs", that's actually an interesting question: in theory the compiler could infer a parameter for each reference, for example. There is a pretty big problem though: lifetimes are part of the type system, so changes to even a private field now cause compilation errors elsewhere, including in a dependant crate that you won't find out about until later. It's the same reason you need to opt in to derivable traits like Copy: you're making a compatibility guarantee, so be explicit about it.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.