0

I have a rusqlite connect in a mutex

as follows:

struct MyStruct {
    connection: std::sync::Mutex<rusqlite::Connection>,
}

When I'm finished with it I want to close it, which I attempted to do as follows:

let lock_ro = mystruct.connection.lock().unwrap();
lock_ro.close()
.map_err(|e| e.1)
.with_context(|| format!("failed to close))?;

However I get this error:

error[E0507]: cannot move out of dereference of std::sync::MutexGuard<'_, rusqlite::Connection>

and: ^^^^^^^ move occurs because value has type rusqlite::Connection, which does not implement the Copy trait

If I can't move it how can I close it?

trampster
  • 8,598
  • 4
  • 37
  • 52
  • `.close()` takes ownership and destroys the `Connection`, are you fine with destroying `MyStruct` as well? – kmdreko Mar 10 '22 at 03:37
  • No, there could be another thread waiting on the mutex, I need some way for it to know once it gets the lock that the connection is now closed. I was using a bool on MyStruct to confer this information. – trampster Mar 10 '22 at 03:54

1 Answers1

2

If MyStruct is shared between threads when you want to close it, you can store it as an Option:

struct MyStruct {
    connection: std::sync::Mutex<Option<rusqlite::Connection>>,
}

So then when you want to close it, you can take ownership of the value via .take() and then call .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"))?;
kmdreko
  • 42,554
  • 6
  • 57
  • 106