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

标签 rust

<分区>

我正在用 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 会破坏任何东西(老实说,我真的不记得为什么一开始会有它们)。

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

最佳答案

事实证明,我的问题确实是 Why can't I store a value and a reference to that value in the same struct? 的抽象版本我认为使用 RefCells 有点 解决了这个问题,但实际上只是从我这里抽象出了这个问题。

摆脱了 RefCells,删除了生命周期参数,并做了一个小的 Mill 结构来存储 usizes 来索引 Position Vec 与。

关于rust - 添加生命周期参数时借用中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48101033/

相关文章:

rust - 返回响应后,在后台运行长时间运行的异步函数

rust - 有没有办法对多个语句使用 cfg(feature) 检查?

rust - 使用带有 iter().map() 的函数 - 作为命名函数 vs 作为闭包

rust - 在多个目录中组织 Rust 代码时 Unresolved 导入问题

rust - Rust 中的引用分配

rust - 如何在 Rust 中创建一个引用 trait 实现的静态数组?

pointers - 使用rust "Borrowed pointers"语法

algorithm - 获取 BTreeMap 中最大值的键的惯用方法?

rust - 可变字符串的生命周期不足以执行 for 循环

rust - 迭代递归结构时无法获取可变引用 : cannot borrow as mutable more than once at a time