I want to iterate over a vector (or map) of actors in a world struct. The actors need access to the world as they might need to get information about the world, but can also change the state of the world. I should this be done properly in rust?
struct Actor {
}
impl Actor {
pub fn step(&mut self, world: &mut World) {
world.act();
}
}
struct World {
actors: Vec<Actor>,
state: u32
}
impl World {
pub fn step(&mut self) {
for actor in self.actors.iter_mut() {
actor.step(self);
}
}
pub fn act(&mut self) {
self.state += 1;
}
}
fn main() {
}
This code give the error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:18:24
|
17 | for actor in self.actors.iter_mut() {
| ----------------------
| |
| first mutable borrow occurs here
| first borrow later used here
18 | actor.step(self);
| ^^^^ second mutable borrow occurs here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `actors` due to previous error