【发布时间】: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
我知道player 将ship 借用为不可变的,并且在借用发生后我仍在尝试修改ship,但我找不到我应该使用的正确智能指针或包装器对于这种情况?你会使用RwLock,还是RefCell,或者别的什么?
【问题讨论】:
标签: rust reference borrow-checker ownership