【问题标题】:Multiple reference readers and one reference writer in RustRust 中的多个参考阅读器和一个参考作者
【发布时间】:2020-07-17 12:17:17
【问题描述】:

我目前正在开发一个小型 Rust 游戏,从该语言开始,基本上有以下代码(我在这里只写了一个最小的例子):

struct Player<'a> {
    pub ship: &'a Ship<'a>,
}

impl<'a> Player<'a> {
    pub fn run(&mut self) {
        // Does some computing with self.ship.x/self.ship.y
    }
}

struct Ship<'a> {
    pub players: Vec<Player<'a>>,
    pub x: f64,
    pub y: f64,
}

impl<'a> Ship<'a> {
    pub fn add_player(&mut self, player: Player<'a>) {
        self.players.push(player);
    }
}

fn main() {
    let mut ship = Ship {
        players: vec![],
        x: 0.0,
        y: 0.0,
    };

    // At some point create a player for the ship
    let player = Player { ship: &ship };
    ship.add_player(player); // <- Forbidden
}

这里最重要的是所有Players 都可以通过不可变的引用访问他们所属的飞船,这样他们就可以轻松访问他们飞船的位置(x/y)(随着时间的推移而变化) ,随着游戏的运行)。但是,此代码无法编译:

error[E0502]: cannot borrow `ship` as mutable because it is also borrowed as immutable
  --> src/main.rs:32:5
   |
31 |     let player = Player { ship: &ship };
   |                                 ----- immutable borrow occurs here
32 |     ship.add_player(player);
   |     ^^^^^----------^^^^^^^^
   |     |    |
   |     |    immutable borrow later used by call
   |     mutable borrow occurs here

我知道playership 借用为不可变的,并且在借用发生后我仍在尝试修改ship,但我找不到我应该使用的正确智能指针或包装器对于这种情况?你会使用RwLock,还是RefCell,或者别的什么?

【问题讨论】:

    标签: rust reference borrow-checker ownership


    【解决方案1】:

    您的想法是正确的,您可能需要使用 RefCell、RwLock 甚至 Rc。但是,这些概念更高级,我不建议您在刚开始学习该语言时尝试使用它们。相反,我会从 Player 结构中删除 Ship 引用,并让 Ship 包含对 Players 的引用。

    如果你还没有,我强烈推荐official rust book,它是一个很好的语言介绍和很好的例子!

    【讨论】:

    • 谢谢,去看看!仍然对这个问题感到好奇......您是否能够确认像 Vec>> 这样的东西可以解决我的问题,并且没有办法仅通过使用简单的引用来使其工作?跨度>
    • 是的,我相信 Vec>> 会起作用。由于玩家保留了船的借用引用,因此在玩家拥有船时无法对其进行变异,因此,我不相信有任何方法可以使用简单的引用使其工作。
    猜你喜欢
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2021-03-09
    • 2010-11-02
    相关资源
    最近更新 更多