Lifetime error

trait Trait<'a, G> {
    fn get(&'a self) -> G;
}

impl<'a> Trait<'a, &'a u8> for u8 {
    fn get(&'a self) -> &'a u8 {
        self
    }
}

fn foo<'a, T: Trait<'a, &'a u8> + 'a>(t: T) {
    t.get();
}

results in

   |     borrowed value does not live long enough
   |     argument requires that `t` is borrowed for `'a`

I'm having a hard time figuring why calling t.get() is at all going to lead to problems. And I want to be able define a trait with a get where it can possibly return a reference of Self. It's why I am annotating a lifetime on &'a self. But either way, what is that borrow error trying to tell me?

It's beacuse the lifetime annotation is on the function:

fn foo<'a, T: Trait<'a, &'a u8> + 'a>(t: T) {
    t.get(); // desugar to `<T as Trait<'outer, &'outer u8>>::get(&'outer T) -> &'outer u8`
    // You'll never get a reference that can live outside of this function 
    // when T is moved into this function
}

So you need a HRTB to obtain a reference that can live for any lifetime[1] ( Rust Playground )

fn foo<T: for<'a> Trait<'a, &'a u8>>(t: T) {
    t.get(); 
}

  1. or rather any lifetime that may live within the function ↩ī¸Ž

3 Likes

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.