Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on Rust lifetime syntax

Tags:

rust

lifetime

The canonical example I see when dealing with Rust lifetimes is the following func:

pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
   if x.len() > y.len() {
      x
   } else {
      y
   }
}

Interestingly, this seems to translate to "the lifetime of the result of longest() is the shortest lifetime of it's input parameters". The logic makes sense to me but I don't understand how this is communicated by the syntax.

When I look at the function it looks like there is one lifetime 'a and the function seems to be enforcing that x and y must have the exact same lifetime 'a and so the result must have the same lifetime 'a.

I'm not sure if this syntax is essentially syntax sugar for what I'm seeing. If I was allowed to be verbose, then I think the syntax would look something like (it's not correct syntax, I know):

pub fn longest<'a, 'b>(x: &'a str, y: &'b str) -> min('a, 'b) str {
   if x.len() > y.len() {
      x
   } else {
      y
   }
}

Am I understanding this correctly or am I mis-interpreting the language?

like image 679
Kiwi breeder Avatar asked Oct 19 '25 03:10

Kiwi breeder


1 Answers

A lifetime parameter of 'a means that the reference needs to live for at least the lifetime 'a. It's fine to pass in a reference that lasts longer than 'a.

When the function longest() is called, the compiler needs to infer the lifetime 'a from the concrete parameters that are passed in. The compiler is smart enough to infer this lifetime as the intersection of the actual lifetimes of x and y, making sure each parameter satisfies the lifetime bounds.

In essence, this means your interpretation is right.

like image 91
Sven Marnach Avatar answered Oct 22 '25 04:10

Sven Marnach



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!