rust 无法作为不可变借用,因为它也作为可变借用错误

9avjhtql  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(174)

我怎样才能使下面的代码编译,我做错了什么?

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试图在这里执行什么编程范式?

yjghlzjz

yjghlzjz1#

正如评论中所解释的,使用split_first_mut

use rand::seq::SliceRandom;

fn try_attack(game_state: &mut GameState) {
    let mut rng = rand::thread_rng();

    let (player, rest) = game_state.kingdoms.split_first_mut().unwrap();

    let target = rest.choose(&mut rng).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;
    }
}

这也使用了SliceRandom::choose

相关问题