How to store rusqlite Connection and Statement objects in the same struct in Rust? [duplicate]

Let’s look at Connection::prepare:

pub fn prepare<'a>(&'a self, sql: &str) -> Result<Statement<'a>>

If we ignore the Result (which just means that this function can fail), this means “return a Statement that can live no longer than the Connection that prepare was called on”. This is likely due to the Statement containing a reference to the Connection.

However, if you have a reference to an item, then you can no longer move the item because the reference would be invalidated. Using that invalid reference would lead to memory unsafety, so it’s prevented.

Basically, you need to mirror the lifetimes and ownership of these objects in your code, and so you cannot bundle the Connection and Statement in the same structure. Instead, one can reference the other.

Leave a Comment