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

问题描述 投票:1回答:1

我正在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的可变和不可变引用,以及对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字段。

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

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

我很确定这与该方法中的显式生命周期有关,但在我所有的阅读中,我无法让它工作或理解什么是无效的。这很令人困惑,因为没有我没有任何借贷错误。我也不清楚,如果让RefCells的磨机组破坏任何东西(我实际上不记得为什么它们首先在它们中是诚实的)。

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

rust
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

© www.soinside.com 2019 - 2024. All rights reserved.