gpt4 book ai didi

rust - 添加生命周期参数时借用中断

转载 作者:行者123 更新时间:2023-11-29 08:20:53 25 4
gpt4 key购买 nike

<分区>

我正在用 Rust 实现棋盘游戏 Nine Man's Morris。我有一个 Game拥有 Board 的结构结构。 Board存储 RefCell<HashSet>Position 的引用结构。 BoardGame共享生命周期参数。

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_millsp2_mills字段,和 can_mill引用 can_mill字段。

如果我删除 update_mills来电game_loop ,代码编译。有了它,我得到了

cannot borrow *self as mutable because self.board is also borrowed as immutable.

我很确定这与该方法的显式生命周期有关,但在我所有的阅读中,我无法让它工作或理解什么不起作用。这很令人困惑,因为如果没有,我就不会收到任何借用错误。我也不清楚是否在 RefCell 中设置了磨机s 会破坏任何东西(老实说,我真的不记得为什么一开始会有它们)。

我知道这很复杂,但我真的很感激能得到一些帮助。我试图用一个更简单的例子重现这个问题,但遗憾的是没成功。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com