Any good example of using multiple lifetimes in a function?

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:

struct Mut<'a> {
    ref_mut: &'a mut u64,

fn replace_mut<'a, 'b>(place: &'b mut Mut<'a>, value: Mut<'a>) {
    *place = value;

The same applies if the inner reference is not mutable, too; the 'a just has to appear inside the referent of a mutable reference.


A practical example of those are iterators.

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.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.