首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >铁锈/ rusqlite:不能从共享引用中移出

铁锈/ rusqlite:不能从共享引用中移出
EN

Stack Overflow用户
提问于 2022-05-29 08:26:59
回答 1查看 125关注 0票数 0

我将连接包装在结构属性中的一个选项中,并且关闭连接时遇到了困难。我在堆叠溢出区检查了很多关于一般问题的答案,但我无法让它解决我的问题。

下面是一个重现错误的最小示例:

代码语言:javascript
复制
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"] })

代码语言:javascript
复制
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()如下所示:

代码语言:javascript
复制
   /// 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))
    }

如何在不更改一般体系结构的情况下修复此错误,即将连接包装在结构属性中的选项中,并通过实现方法关闭连接?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-29 08:38:03

The Connection::close method消耗self,因此您必须将包装好的值从self.c中取出,以便调用closetake之后,c变成None

代码语言:javascript
复制
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();
}

Documentation of std::option::Option::take

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72422065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档