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.
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.
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.