Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable structs in a vector

Tags:

I'm trying to create a vector to keep track of enemies in a game that will hold a bunch of mutable structs. I have a world struct that has the enemies as a member of it as follows:

pub struct World {
  pub player      : Creature,
  pub enemies     : Vec<Creature>,
}

I create the enemies vector as follows:

 let mut enemies = vec![];
 let mut enemy = Creature::new(5, 5, map_start_x+5, map_start_y+5, "$", 10, 1, "")
 enemies.push(enemy);

later on in the code when I pull out an individual enemy from enemies for attacking and try to update the hp as follows:

  for enemy in self.enemies.iter() {
    if new_x == enemy.x && new_y == enemy.y {
      enemy.hp -= self.player.damage;
      return;
    }
  }

which is where the problem occurs since enemy is apparently not mutable at this point

 error: cannot assign to immutable field `enemy.hp`