【发布时间】:2016-04-29 10:42:16
【问题描述】:
我正在尝试了解 Rust 的所有权模型。在结构上调用函数时,我试图传递对包含对象的引用。
这是我的结构:
pub struct Player {}
impl Player {
pub fn receive(self, app: &App) {
}
}
如您所见,receive 期望引用 App 对象。
pub struct App {
pub player: Player,
}
impl App {
pub fn sender(self) {
// how to call player.test() and pass self as a reference?
self.player.receive(&self);
}
}
上面的代码给了我“使用部分移动的值:self”。这是有道理的,因为App 具有移动语义,因此在调用sender 函数时会将值移动到该函数中。
如果我将其更改为 sender 改为引用 self,我会得到“无法移出借用的内容”,这也是有道理的,因为我们在何时借用了对 self 的引用我们进入了sender 函数。
那我该怎么办?我明白为什么我不能在Player 中存储对App 的引用,因为这会导致双链接结构。但是我应该可以借用一个引用并对其进行操作,不是吗?
我在官方教程中找不到答案。
我通过在receive 中传递self 作为参考解决了这个问题。但是如果我想让app 在receive 中是可变的呢?我不能在sender 中将self 作为可变传递,因为我还借用player 作为可变。
【问题讨论】: