Lifetime anotations incompatible with trait signature

Is there a way to get around this problem without rewriting the trait ?

struct Foo<'a>(Option<&'a str>);

trait Bar {
    fn bar(&mut self, value: &str);
}

impl<'a> Bar for Foo<'a> {
    fn bar(&'a mut self, value: &'a str) {
       self.0 = Some(value);
    }
}
error[E0308]: method not compatible with trait
  --> src/lib.rs:10:5
   |
10 |     fn bar(&'a mut self, value: &'a str) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected signature `fn(&mut Foo<'_>, &_)`
              found signature `fn(&'a mut Foo<'_>, &'a _)`

No, the signature of the trait does not allow you to store the reference after the method is called.

As an aside, try to avoid mutable references like &'a mut Foo<'a> (there both the reference and the type have the same lifetime) like the one that results from your &'a mut self argument, they are pretty much always wrong and will lead to errors when you actually need to create them to call the method.

4 Likes