Consider this toy example of "fighting" two random "players":
#[derive(Clone)]
struct Player {
name: String,
health: i32,
attack: i32,
}
fn fight(player_a: &mut Player, player_b: &mut Player) {
player_a.health -= player_b.attack;
player_b.health -= player_a.attack;
}
fn main() {
// Create Vector of 100 new players
let players: Vec<Player> = vec![
Player {
name: String::new(),
health: 100,
attack: 5,
};
100
];
// Pick two "random" indices
let i1 = 19;
let i2 = 30;
fight(&mut players[i1], &mut players[i2]); // Error!
}
This code will not work as the fight
function takes two mutable references to elements of the same players
vector.
My ugly workaround currently looks like the following, using RefCell
:
use std::cell::RefCell;
let mut players: Vec<RefCell<Player>> = vec![];
for _ in 0..100 {
players.push(RefCell::new(Player {
name: String::new(),
health: 100,
attack: 5,
}));
}
fight(&mut players[i1].borrow_mut(), &mut players[i2].borrow_mut());
I'd like to know if there's a more efficient way of doing this to avoid the extra overhead of RefCell
? Can I leverage split_at_mut
somehow?