我将连接包装在结构属性中的一个选项中,并且关闭连接时遇到了困难。我在堆叠溢出区检查了很多关于一般问题的答案,但我无法让它解决我的问题。
下面是一个重现错误的最小示例:
use rusqlite::Connection;
struct Db {
c: Option<Connection>
}
impl Db {
pub fn new() -> Self {
return Db { c: None }
}
pub fn open(&mut self) {
self.c = Some(Connection::open("test.db").unwrap());
}
pub fn close(&mut self) {
self.c.as_ref().unwrap().close();
}
}
fn main() {
let mut d= Db::new();
d.open();
d.close();
}我得到以下输出,使用Rust 1.61.0 (Arch Linux rust 1:1.61.0-1)和Cargo和rusqlite (rusqlite = { version = "0.27.0", features = ["bundled"] })
error[E0507]: cannot move out of a shared reference
--> foo.rs:18:9
|
18 | self.c.as_ref().unwrap().close();
| ^^^^^^^^^^^^^^^^^^^^^^^^^-------
| | |
| | value moved due to this method call
| move occurs because value has type `Connection`, which does not implement the `Copy` trait
|
note: this function takes ownership of the receiver `self`, which moves value
--> ~.cargo/registry/src/github.com-1ecc6299db9ec823/rusqlite-0.27.0/src/lib.rs:725:18
|
725 | pub fn close(self) -> Result<(), (Connection, Error)> {
| ^^^^
For more information about this error, try `rustc --explain E0507`.输出引用的rusqlite库中的函数close()如下所示:
/// Close the SQLite connection.
///
/// This is functionally equivalent to the `Drop` implementation for
/// `Connection` except that on failure, it returns an error and the
/// connection itself (presumably so closing can be attempted again).
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite call fails.
#[inline]
pub fn close(self) -> Result<(), (Connection, Error)> {
self.flush_prepared_statement_cache();
let r = self.db.borrow_mut().close();
r.map_err(move |err| (self, err))
}如何在不更改一般体系结构的情况下修复此错误,即将连接包装在结构属性中的选项中,并通过实现方法关闭连接?
发布于 2022-05-29 08:38:03
The Connection::close method消耗self,因此您必须将包装好的值从self.c中取出,以便调用close。take之后,c变成None。
use rusqlite::Connection;
struct Db {
c: Option<Connection>,
}
impl Db {
pub fn new() -> Self {
return Db { c: None };
}
pub fn open(&mut self) {
self.c = Some(Connection::open("test.db").unwrap());
}
pub fn close(&mut self) {
self.c.take().unwrap().close().unwrap();
}
}
fn main() {
let mut d = Db::new();
d.open();
d.close();
}https://stackoverflow.com/questions/72422065
复制相似问题