My goal is to return a mutable reference to a trait obejct that is stored in a Box.
This seems related to this question about borrowing references to optional struct members, the main difference, however, seems to be the presence of a trait object. I'm also trying to return an Option instead of a Result.
Trying to use the same approach seems to lead to a lifetime issue.
Sample code:
trait Baz {}
#[derive(Debug)]
struct Foo;
impl Baz for Foo {}
struct Bar {
data: Option<Box<Baz>>,
}
enum BarErr {
Nope,
}
impl Bar {
fn borrow_mut(&mut self) -> Option<&mut Baz> {
self.data.as_mut().map(|x| &mut **x)
}
}
Error message:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:20:9
|
20 | self.data.as_mut().map(|x| &mut **x)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected type `std::option::Option<&mut dyn Baz>`
found type `std::option::Option<&mut (dyn Baz + 'static)>`
note: the anonymous lifetime #1 defined on the method body at 19:5...
--> src/lib.rs:19:5
|
19 | / fn borrow_mut(&mut self) -> Option<&mut Baz> {
20 | | self.data.as_mut().map(|x| &mut **x)
21 | | }
| |_____^
= note: ...does not necessarily outlive the static lifetime
I can't really see where the lifetime would get extended.
Also trying to replace &mut **x
with as_mut
does not help.