同时且可变地访问同一结构的不同字段

时间:2017-08-29 09:06:18

标签: rust mutable borrow-checker lifetime-scoping

我试图在Rust写一个纸牌游戏但是在借阅检查器上遇到了一些麻烦。我的主structGame,看起来像这样

struct Game {
    players: HashMap<String, Player>,
    deck: Vec<Card>,
}

播放器就像是

struct Player {
    hand: Vec<Card>,
}

为简单起见,我们可以假设Card看起来像

struct Card {
    text: String,
}

现在我很自然地想从Game.deck

中抽取牌
impl Game {
    fn draw_cards(&mut self, num: usize) -> Option<Vec<Card>> {
        if self.deck.len() >= num {
            let mut cards: Vec<Card> = Vec::new();
            for _ in 0..num {
                cards.push(self.deck.pop().unwrap());
            }
            Some(cards)
        } else {
            None
        }
    }
}

并将它们附加到玩家的手中

impl Game {
    fn draw_to_player(&mut self, name: &String, num: usize) -> Result<(), ()> {
        let cards = self.draw_cards(num);
        match cards {
            Some(mut cards) => {
                let player = self.players.get_mut(name);
                match player {
                    Some(player) => {
                        player.hand.append(&mut cards);
                        Ok(())
                    },
                    None => Err(()),
                }
            },
            None => Err(()),
        }
}

Complete playground example

到目前为止,一切都很好。在开始游戏时,我想迭代所有玩家并让他们画出他们的起手牌:

fn draw_for_all(&mut self) {
    for name in self.players.keys() {
        self.draw_to_player(name, 2);
    }
}

Complete playground example

这不起作用,因为在迭代密钥时借用self,但必须可变地借用来调用draw_to_player

error[E0502]: cannot borrow `*self` as mutable because `self.players` is also borrowed as immutable
  --> src/main.rs:48:13
   |
47 |         for name in self.players.keys() {
   |                     ------------ immutable borrow occurs here
48 |             self.draw_to_player(name, 2);
   |             ^^^^ mutable borrow occurs here
49 |         }
   |         - immutable borrow ends here

我怎么能解决这个问题?

0 个答案:

没有答案