Variable structure in vector

I'm trying to create a vector to track enemies in games that will have a bunch of variable structures I have a world structure whose enemies, as its members, are as follows:

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

I create enemy vectors 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, in the code, I pulled out an enemy from the enemy to attack and tried to update HP, as shown below:

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

This is where the problem occurs, because the enemy is obviously immutable at this time

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

Solution

Updated the latest rust version

Variability in rust is independent of data structure. It is the attribute of the place where data is stored (read: variable) That is, if you place a value in the variable slot:

let mut world = World::new();

Then you can make a variable reference to this variable and call the method that can change it

Your structure has all the data it contains, so you can make it variable at any time self. enemies. ITER () returns an iterator that generates items of type & Creation - immutable references, so you can't use them to change the structure However, there is another method on the vector, called ITER_ mut(). This method returns an iterator that generates & mut creation – mutable references that allow you to change the 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;
  }
}

Please note that in order for it to work, you must pass self through variable references, otherwise nothing under it will be changed, which means that you will not be able to obtain variable references inside the structure, including project vectors In short, make sure that any method that contains this loop is defined as follows:

fn attack(&mut self,...) { ... }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>