I need to iterate over a vector of mutable references; here is a simplified reproduction:
trait Ticking {
fn tick(&mut self);
}
trait Fish {}
struct World<'a> {
fish: Vec<&'a mut dyn Fish>,
}
impl<'a> Ticking for World<'a> {
fn tick(&mut self) {
let _fish: &mut dyn Fish = self.fish[0];
//let _fish: &mut dyn Fish = self.fish.get_mut(0).expect("expected value");
}
}
struct Guppy<'a> {
n_ref: &'a usize,
}
impl<'a> Fish for Guppy<'a> {}
fn main() {
let mut guppy: Guppy = Guppy { n_ref: &5 };
let _world: World = World {
fish: vec![&mut guppy],
};
}
I received the following error:
error[E0596]: cannot borrow data in an index of `std::vec::Vec<&mut dyn Fish>` as mutable
--> src/main.rs:15:36
|
15 | let _fish: &mut dyn Fish = self.fish[0];
| ^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::vec::Vec<&mut dyn Fish>`
I attempted to call get_mut
directly and received a lifetime bound error:
error[E0277]: the trait bound `&'a mut (dyn Fish + 'a): Fish` is not satisfied
--> src/main.rs:13:36
|
13 | let _fish: &mut dyn Fish = self.fish.get_mut(0).expect("expected value");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Fish` is not implemented for `&'a mut (dyn Fish + 'a)`
|
= note: required for the cast to the object type `dyn Fish`
The compiler explanations were unhelpful in determine the root cause here.