首页 文章

添加生命周期参数时,借用中断[重复]

提问于
浏览
1

这个问题在这里已有答案:

我正在Rust中实现Nine Man's Morris的棋盘游戏 . 我有一个拥有 Board 结构的 Game 结构 . Board 存储 PositionPosition 结构的引用 . 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 的可变和不可变引用,以及 Board 上的2次调用:

pub fn can_mill(&self) -> bool {}
pub fn update_mills(&'a self, player_id: i8) {}

update_mill 更新 p1_millsp2_mills 字段, can_mill 引用 can_mill 字段 .

如果我删除 game_loop 中的 update_mills 调用,代码将编译 . 有了它,我明白了

不能借用* self作为可变因为self.board也被借用为不可变的 .

我_983371已经能够让它工作或理解什么是't working. It'令人困惑,因为没有我't get any borrowing errors. I' m也不清楚 RefCell 中的磨机组是否打破任何东西(我实际上不记得为什么它们在其中首先要说实话) .

我意识到这是非常复杂的,但我真的很感激一些帮助 . 我试图用一个更简单的例子重新创建这个问题,但不能遗憾 .

1 回答

  • 0

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

    摆脱了RefCells,删除了生命周期参数,并制作了一个 Mill 结构,存储 usizes 以索引 Position Vec .

相关问题