Here's a very simple stab at a game loop in Rust:
trait Entity {
fn update(&mut self, world: &mut World);
}
struct World {
entities: Vec<Box<Entity>>
}
impl World {
fn update(&mut self) {
for ent in self.entities.iter_mut() {
ent.update(self);
}
}
}
This, however, does not work:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> test.rs:12:16
|
11 | for ent in self.entities.iter_mut() {
| ------------- first mutable borrow occurs here
12 | ent.update(self);
| ^^^^ second mutable borrow occurs here
13 | }
| - first borrow ends here
error: aborting due to previous error
In order to get the entity out of the vector, I need to do a mutable borrow of the World
struct, which prevents the entity from using it in any way.
What would be a good way to structure this, so that I can both mutate the entity as well as have the entity reference other objects in the world (for collision checking, etc)?
The only way I can think of is to either have the entity return an updated copy of itself (I don't think all that allocating and copying would be good for performance) or cowboy it with unsafe
.