我是 Rust 的新手,我正在使用 Postgres 板条箱。我正在尝试围绕 PostgreSQL 客户端创建一个包装器,并且我已经定义了这个结构:
pub struct PostGresSqlClient {
user_name: String,
host_name: String,
port: String,
client: Client,
}
后来,我试图在这个结构上实现 Drop trait。现在,它只是尝试关闭与客户端的连接,但稍后它可能会做不同的事情。
impl Drop for PostGresSqlClient {
fn drop(&mut self) {
self.client.close();
}
}
但是,我遇到了这个问题:
error[E0507]: cannot move out of `self.client` which is behind a mutable reference
--> data_lib/src/lib.rs:106:13
|
106 | self.client.close();
| ^^^^^^^^^^^ move occurs because `self.client` has type `Client`, which does not implement the `Copy` trait
我不知道如何解决这个问题,任何帮助将不胜感激。
回答1
您不需要这样做,来自 https://docs.rs/postgres/latest/postgres/struct.Client.html#method.close:
关闭客户端与服务器的连接。
这相当于客户端的 Drop 实现,只是它将遇到的任何错误返回给调用者。
Client
连接在删除时已经关闭,您的内部 Client
将与外部连接一起被删除。
认为 close
需要一个拥有的 Client
(self
),它将在函数调用后被删除。