我正在尝试讨论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
的引用,因为这会导致双向链接结构。但我应该可以借用一个参考并对其进行操作,不是吗?
我在官方教程中找不到答案。
我通过self
作为参考receive
解决了它。但是,如果我想app
在receive
中可变吗?我无法通过self
在sender
可变,因为我也借用player
为可变。