2
Self: Sized + 'a 

or

T: T + 'a

Seen this syntax while following a tutorial which suggests using rust 2018 edition instead of 2021 if it is related to your answer. However, I can not find the meaning of + lifetime parameter syntax.

yokus
  • 145
  • 2
  • 10
  • Does this similar question help answer your question? https://stackoverflow.com/questions/22048673/ – zedfoxus Jul 01 '23 at 23:15
  • No, I know about lifetimes, just the + syntax is not mentioned anywhere I looked. Thanks anyway. – yokus Jul 02 '23 at 00:36

1 Answers1

4

It means that whatever type you use in the generic must outlive 'a, which means that all references it contains must outlive 'a. Here's some types that will always work.

i32                 // contains no lifetimes, so all zero lifetimes outlive 'a
Vec<u8>             // same as above
&'static str        // 'static outlives all lifetimes
SomeStruct<'static> // same as above

Here's some types that will only work if their lifetimes outlive 'a.

Vec<&'b u8>               // 'b must outlive 'a
&'c str                   // 'c must outlive 'a
SomeStruct<'d>            // 'd must outlive 'a
AnotherStruct<'x, 'y, 'z> // all lifetimes must outlive 'a

This is most often used with + 'static, which means "all contained lifetimes must be 'static". You may also see it on trait objects like Box<dyn Error + 'a> and impl Trait types like impl Iterator<Item = u8> + 'a, where it means "this type only lives for 'a", just like a regular lifetime parameter.

I don't think anything about this has changed since the 2018 edition.

drewtato
  • 6,783
  • 1
  • 12
  • 17
  • Do you also have an official explanation. Thank you for this one. – yokus Jul 02 '23 at 00:37
  • 1
    @yokus https://doc.rust-lang.org/reference/trait-bounds.html – drewtato Jul 02 '23 at 01:32
  • It's worth adding that the name `'a` for the lifetime is arbitrary. Often lifetime specifiers are named in alphabetical order, but that's just a questionable convention. You can also give them more descriptive names such as `'serialization` or `'inner_borrow` depending on the lifetime they describe. In the given example, `'b` must not outlive `'a`, because `b` comes after `a` in the alphabet, but because of the lifetime constraints introduced by the program structure. – Richard Neumann Jul 02 '23 at 17:13
  • Thank you for your time and answer with reference. Really appreciate it! :) – yokus Jul 03 '23 at 06:48