Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does + 'a lifetime syntax do in rust?

Tags:

rust

lifetime

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.

like image 284
yokus Avatar asked Sep 14 '26 20:09

yokus


1 Answers

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.

like image 161
drewtato Avatar answered Sep 20 '26 13:09

drewtato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!