Hey everyone,
I'm new to Rust and am trying to get a better grasp of the language by applying it on design patterns.
I came across an error which I couldn't solve, as shown with the simplified code below:
pub trait MyTrait {
fn get_attr(&self) -> &mut Vec<&Box<dyn MyTrait>>;
fn my_method(&self); // Makes use of `self.get_attr()`
}
pub struct MyStruct<'a> {
my_attr: Vec<&'a Box<dyn MyTrait>>,
}
impl<'a> MyStruct<'a> {
pub fn new() -> Self {
MyStruct {
my_attr: Vec::new(),
}
}
}
impl<'a> MyTrait for MyStruct<'a> {
fn get_attr(&self) -> &mut Vec<&Box<dyn MyTrait>> {
&mut self.my_attr
}
fn my_method(&self) {
...
}
The borrow checker instructed me to add a lifetime specifier to my_attr
of MyStruct
, which I did.
However, that led to the error below, which I do not know how to resolve:
error[E0308]: mismatched types
--> src/sample.rs:17:9
|
17 | &mut self.my_attr
| ^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected mutable reference `&mut Vec<&Box<(dyn MyTrait + 'static)>>`
found mutable reference `&mut Vec<&'a Box<(dyn MyTrait + 'static)>>`
note: the anonymous lifetime defined here...
--> src/sample.rs:16:17
|
16 | fn get_attr(&self) -> &mut Vec<&Box<dyn MyTrait>> {
| ^^^^^
note: ...does not necessarily outlive the lifetime `'a` as defined here
--> src/sample.rs:15:6
|
15 | impl<'a> MyTrait for MyStruct<'a> {
| ^^
Appreciate it if someone can explain what I'm doing incorrectly here, or suggest a better way to go about my program structure.
Much thanks in advance!