我在互斥体中有一个粗糙的连接。
如下所示:
struct MyStruct {
connection: std::sync::Mutex<rusqlite::Connection>,
}当我完成它时,我想关闭它,我试图这样做:
let lock_ro = mystruct.connection.lock().unwrap();
lock_ro.close()
.map_err(|e| e.1)
.with_context(|| format!("failed to close))?;然而,我得到了这个错误:
errorE0507:无法脱离
std::sync::MutexGuard<'_, rusqlite::Connection>的引用
并且:^移动是因为值的类型为rusqlite::Connection,它没有实现Copy特性。
如果我不能移动它,我怎么能关闭它?
发布于 2022-03-10 04:13:14
如果要在线程之间共享MyStruct,则可以将其存储为Option。
struct MyStruct {
connection: std::sync::Mutex<Option<rusqlite::Connection>>,
}因此,当您想关闭它时,您可以通过.take()获取该值的所有权,然后调用.close()
mystruct.connection
.lock()
.expect("lock should not be poisoned")
.take()
.expect("there should be a connection")
.close()
.map_err(|e| e.1)
.with_context(|| format!("failed to close"))?;https://stackoverflow.com/questions/71418497
复制相似问题