I'm coding a little game; I have a vector of monsters and a monster can deal damage to all other monsters. I need a function that takes the vector of all monsters and a reference to the monster that is attacking.
I understand why this is not possible with the type system of Rust: I need a mutable reference to the vector and a mutable reference to the monster, but this is not possible because the monster belongs to the vector. I can not find a workaround.
struct Monster {
life: i32,
}
// give 1 damage to all except me
// increase my life by 1
fn give_1_damage(me: &mut Monster, all: &mut Vec<Monster>) {
for m in all {
m.life -= 1;
}
me.life += 2;
}
fn main() {
let mut a = vec![Monster { life: 3 }, Monster { life: 3 }];
let ref mut b = &mut a[0];
give_1_damage(b, &mut a);
}
Lukas Kalbertodt proposes to pass the offset of the monster in the vector. This works great, thanks! But in fact my code is more complicated:
struct Monster {
life: i32,
}
struct Game {
player1: Vec<Monster>,
player2: Vec<Monster>,
}
fn give_1_damage(player_idx: usize, monster_idx: usize, game: &mut Game) {
// ...
}
I know that it's possible to pass the index of the player, and the index of the monster, but I found this is ugly. Do I really need to pass the player_idx
and the monster_idx
whereas I previously know which monster is attacking and I can have a reference to it?