<分区>
我正在用 Rust 实现棋盘游戏 Nine Man's Morris。我有一个 Game
拥有 Board
的结构结构。 Board
存储 RefCell<HashSet>
对 Position
的引用结构。 Board
和 Game
共享生命周期参数。
pub struct Board<'a> {
pub positions: Vec<Position>,
pub ids_to_positions: HashMap<String, usize>,
p1_mills: RefCell<HashSet<(&'a Position, &'a Position, &'a Position)>>,
p2_mills: RefCell<HashSet<(&'a Position, &'a Position, &'a Position)>>,
can_mill: Cell<bool>,
}
pub struct Game<'a> {
pub board: Board<'a>,
pub player1: Player,
pub player2: Player,
current_player_id: i8,
}
Game::game_loop
循环执行一组方法(获取输入、更新棋盘等),直到游戏结束。这一直工作正常,因为我已经向它添加了方法。
impl<'a> Game<'a> {
pub fn print(&self) {
self.board.print();
}
pub fn game_loop(&'a mut self) {
loop {
self.print();
self.make_move();
print!("can_mill: {}", self.board.can_mill());
self.board.update_mills(self.current_player_id);
self.switch_player();
}
}
pub fn make_move(&mut self) {}
pub fn switch_player(&self) {}
}
混合了对 self
的可变和不可变引用的方法, 和 2 个调用 Board
:
pub fn can_mill(&self) -> bool {}
pub fn update_mills(&'a self, player_id: i8) {}
update_mill
更新 p1_mills
和 p2_mills
字段,和 can_mill
引用 can_mill
字段。
如果我删除 update_mills
来电game_loop
,代码编译。有了它,我得到了
cannot borrow
*self
as mutable becauseself.board
is also borrowed as immutable.
我很确定这与该方法的显式生命周期有关,但在我所有的阅读中,我无法让它工作或理解什么不起作用。这很令人困惑,因为如果没有,我就不会收到任何借用错误。我也不清楚是否在 RefCell
中设置了磨机s 会破坏任何东西(老实说,我真的不记得为什么一开始会有它们)。
我知道这很复杂,但我真的很感激能得到一些帮助。我试图用一个更简单的例子重现这个问题,但遗憾的是没成功。