我怎样才能拥有某物的所有权并调用它的方法来移动该对象?

问题描述 投票:0回答:1

我有以下代码,该代码无法编译,因为调用“self.client.dispose()”会移动对象“client”,因为 dispose 具有此签名:dispose(self)。这附近还有吗?我想处理该客户端,以便我可以创建一个新客户端并将其分配回 self.client 字段。客户端不是复制或克隆 - 它是我无法更改的真正的 PITA 第三方代码。

// third party crate
struct Client { ... }
impl Client {
   async fn dispose(self) -> Result<..> {...}
}

// My code starts here 

struct MyStruct {
  client: Client
}

impl MyStruct {
  async fn do_something(&mut self) -> Result<...> {
     // stuff
     let thing = self.client.create();
     match thing {
        ...
        Err(error) => {
          // recover here by recreating the client, first disposing it
          self.client.dispose().await?; <--- not possible, client is moved

          self.client = Client::new(); // somehow mutate self with new Client
        }
     }
  } 
}

我尝试将客户端字段设置为 Cell、RefCell、Arc、Mutex、Box of Client。我想如果有人可以非常好心地为我重写这个,这样就可以处理客户端并创建一个新的客户端来改变 self.client,然后我可以尝试从中学习。

非常感谢。

rust borrow-checker
1个回答
0
投票

如果您要替换的值不依赖于之前的值,则只需使用

std::mem::replace
(如果实现了
std::mem::take
,则使用
Default
)。

let prev_client = std::mem::replace(&mut self.client, Client::new());

// You now have the `Client` that was previously in `self` but has been replaced
// with a different value. You can now do whatever you like with it, prev_client
// is the owner now.
prev_client.dispose().await?;
© www.soinside.com 2019 - 2024. All rights reserved.