我怎样才能使下面的代码编译,我做错了什么?
fn try_attack(game_state: &mut GameState) {
let mut rng = rand::thread_rng();
let length = game_state.kingdoms.len();
let player = game_state.kingdoms.first_mut().unwrap();
let target = game_state
.kingdoms
.get(rng.gen_range(1..length) as usize)
.unwrap();
if target.soldiers < player.soldiers || target.gold < player.gold {
player.gold += (target.gold as f64 * 0.1) as u32;
player.soldiers += (target.soldiers as f64 * 0.05) as u32;
}
}
我得到的错误:
error[E0502]: cannot borrow `game_state.kingdoms` as immutable because it is also borrowed as mutable
--> src\game_utils.rs:85:18
|
83 | let player = game_state.kingdoms.first_mut().unwrap();
| ------------------------------- mutable borrow occurs here
84 |
85 | let target = game_state
| __________________^
86 | | .kingdoms
87 | | .get(rng.gen_range(1..length) as usize)
| |_______________________________________________^ immutable borrow occurs here
...
90 | if target.soldiers < player.soldiers || target.gold < player.gold {
| --------------- mutable borrow later used here
我知道编译器不喜欢我借用一些不可变的东西,当我借用一些可变的东西时,但是如果我想从 Realm 向量中得到一个随机目标,我需要这样做。
正确的方法是什么?rust试图在这里执行什么编程范式?
1条答案
按热度按时间yjghlzjz1#
正如评论中所解释的,使用
split_first_mut
。这也使用了
SliceRandom::choose
。