Hello!
All the examples of using lifetime in function are finally requiring only one lifetime for both input lifetime and output lifetime.
Will there be any good example that we MUST use multiple lifetimes in one function?
What I found was something like this but the function only requires lifetime 'a
static ZERO: i32 = 0;
struct Foo<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
fn get_x_or_zero_ref<'a>(x: &'a i32, y: &i32) -> &'a i32 {
if *x > *y {
return x
} else {
return &ZERO
}
}
fn main() {
let x = 1;
let v;
{
let y = 2;
let f = Foo { x: &x, y: &y };
v = get_x_or_zero_ref(&f.x, &f.y);
}
println!("{}", *v);
}
A common example is when you have a mutable reference to a type itself containing a mutable reference. In this case, you don't want the &'a mut T<'a> anti-pattern to manifest, so you'll write two lifetimes:
If you have a borrowing type with &self-or-&mut self-based methods more generally, you usually want to return the inner lifetime (even in the non-mut case). Otherwise callers may not be able to get a long enough lifetime for their own needs.