When you create a function with multiple references as inputs, and return a reference as an output, you need to specify which one, or multiple input references the lifetime of the output reference is tied to. This makes sense.
The thing that doesn't make sense is why you would ever need to define more than one generic lifetime. You can only ever have one return value.
Here, we define both 'a
and 'b
- two generic lifetimes. On the return value, we can either specify 'a
or 'b
- not both:
fn foo<'a, 'b>(ref1: &'a str, ref2: &'b str) -> &'a str {}
It seems like this could be shortened to:
fn foo<'a>(ref1: &'a str, ref2: &str) -> &'a str {}
If we wanted to tie the lifetime of the output to the second input argument instead, we could do:
fn foo<'a>(ref1: &str, ref2: &'a str) -> &'a str {}
If we wanted to tie it to both, we can do:
fn foo<'a>(ref1: &'a str, ref2: &'a str) -> &'a str {}
This covers every scenario (at least in this simple example), and none of these require defining more than one generic lifetime (defining 'b
).
Is there ever a case where you do need to define more than one generic lifetime?