gpt4 book ai didi

rust - 无法移出定义 `Drop` 特征的类型 [E0509]

转载 作者:行者123 更新时间:2023-11-29 08:04:04 24 4
gpt4 key购买 nike

我有以下使用 rust-postgres 的 Rust 代码打算在我的结构超出范围后提交事务

struct SqlTransaction<'a> {
connection: &'a Connection,
transaction: Transaction<'a>,
}

impl<'a> Drop for SqlTransaction<'a> {
fn drop(&mut self) {
let result = self.transaction.commit();
match result {
Ok(_) => print!("herp"),
Error => print!("lol"),

}
}
}

编译器用以下消息提示 commit()

cannot move out of type `SqlTransaction<'a>`, which defines the `Drop` trait [E0509]at line 12 col 22

发生了什么,我该如何解决?

最佳答案

Transaction::commit 方法 consumes the transaction :

pub fn commit(self) -> Result<()> {
self.set_commit();
self.finish()
}

如果您能够调用commit,那么self 的值将处于某种不一致的状态,因为self.transaction 是什么?搬走了!

如果类型没有实现Drop,这就不是问题,因为编译器只会删除结构的所有其他部分。但是,由于它实现了 Drop,因此您永远无法拆开结构,因为 Drop 无法运行!当您在 Drop 实现本身中时,这甚至适用。

如果您确实需要这样做,您必须让 transaction 成为您可以轻松替换的某种类型。 Option 是一个不错的选择,因为您可以使用 take 将其替换为 None


Transaction 的特定情况下,您无需执行任何特殊操作。虽然 Transaction 通常会在删除时回滚,但您可以调用 Transaction::set_commit以便它在删除时提交。

关于rust - 无法移出定义 `Drop` 特征的类型 [E0509],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com