我正在嘗試討論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
爲可變。