1

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.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
  • Is it possible to separate the World into two parts, the `entities` and everything else? If you hand out the whole World, the receiver could modify the `entities` and thus invalidate the loop. – kennytm Feb 28 '17 at 04:06
  • @kennytm Well, the entity being updated needs to be able to mutate existing entities (ex. a bullet entity will need to alter the player's health). It seems like the best way according to Francis's link is to use RefCell for the entities in the array. – Colonel Thirty Two Feb 28 '17 at 15:58

0 Answers0