Updated for the latest Rust version
Mutability in Rust is not associated with data structures, it is a property of a place (read: a variable) where the data is stored. That is, if you place a value in a mutable slot:
let mut world = World::new();
then you can take mutable references to this variable, and hence call methods which can mutate it.
Your structure owns all data it contains, so you can make it mutable any time you need. self.enemies.iter()
returns an iterator which generates items of type &Creature
- immutable references, so you can't use them to mutate the structure. However, there is another method on a vector, called iter_mut()
. This method returns an iterator which produces &mut Creature
- mutable references, which do allow changing data they point to.
for enemy in self.enemies.iter_mut() {
if new_x == enemy.x && new_y == enemy.y {
enemy.hp -= self.player.damage;
return;
}
}
// The following also works (due to IntoIter conversion)
for enemy in &mut self.enemies {
if new_x == enemy.x && new_y == enemy.y {
enemy.hp -= self.player.damage;
return;
}
}
Note that in order for this to work, you have to pass self
by mutable reference too, otherwise it will be impossible to mutate anything under it, implying that you won't be able to obtain mutable references to internals of the structure, including items of the vector. In short, make sure that whatever method contains this loop is defined like this:
fn attack(&mut self, ...) { ... }