Lifetime for passing in references to methods

trait Trait<T> {
    fn method(self: Box<Self>, _: T);
}
struct Struct<'a>(Box<dyn Trait<&'a u8>>);
impl<'a> Struct<'a> {
    fn foo(self) {
        let x = 1u8;
        self.0.method(&x);
    }
}

Complains that x is dropped while still borrowed at the end of foo(). The "while still borrowed" is what I think I should correct. I get that 'a on Struct means that 'a must outlive Struct, which x inside foo() definitely does not. But I am unsure how annotate this properly then.

147 | impl<'a> Struct<'a> {
    |      -- lifetime `'a` defined here
148 |     fn foo(self) {
149 |         let x = 1u8;
    |             - binding `x` declared here
150 |         self.0.method(&x);
    |         --------------^^-
    |         |             |
    |         |             borrowed value does not live long enough
    |         argument requires that `x` is borrowed for `'a`
151 |     }
    |     - `x` dropped here while still borrowed

The method call desugars to <dyn Trait<&'a u8> as Trait<&'a u8>>::method(Box<Self>, &'a u8) [1], which means &x must outlive 'a. The error tells you that 'a is outside of the foo method and &x can never live that 'a long.

HRTB can help. Rust Playground


  1. Try it yourself ↩︎

2 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.