Problem about lifetime, please help

I meet a problem about lifetime, I simplified the code as follows

trait TraitCannotChange {
    fn bar(&mut self);
}

struct SomeStruct<'a> {
    ...
    v: &'a [f64],
}
impl <'a> SomeStruct <'a> {
    fn foo(&'a mut self) {
       ...
    }
}
impl <'a> TraitCannotChange for SomeStruct<'a> {
    fn bar(&mut self) {
        self.foo();
    }
}

compilation error:

cannot infer an appropriate lifetime for autoref due to conflicting requirements

note: ...so that the types are compatible
  --> src\main.rs:82:14
   |
82 |         self.foo();
   |              ^^^
   = note: expected `&mut SomeStruct<'_>`
              found `&mut SomeStruct<'a>`

in this demo case, if I add 'a in trait and the '&'a mut self' parameter of fn bar(), It will compile successfully.
But the trait can not be changed because it is a dependency of many other codes. How can I solve this problem without changing definition of the trait. Please help, Thanks.

Do you really need a &'a mut self here? You should be able to use &mut self and be fine

2 Likes

thanks for reply. yes, I need it.
I simplified the code as demo. I need the &'a mut self indeed in the actual code.

Then I guess what you're doing is inherently unsafe. The trait doesn't guarantee the reference you get will be valid for that lifetime, however you really need that lifetime, so any solution that doesn't involve changing the trait or the lifetime requiremente of your function should be unsound.

ps: what are you doing that you really need a &'a mut SomeStruct<'a> ? Note that it's really easy to mess up lifetimes when using these types of borrows (example)

1 Like

Sounds like you are trying to build a self-referential struct, i.e. a struct where one field contains a reference into the struct itself. Such a struct is not possible to write in safe Rust, and you should find a different approach rather than try put the struct's lifetime on &mut self.

2 Likes

Thanks for reply

Thanks for reply, I have changed the struct of code to avoid this problem...