Hi, having some problems with the borrow checker as a newbie in rust! (Shocker to you all, I'm sure~)
I understand lifetime to some degree, but not all the way as I'm sure will become apparent.
So I'm trying to write a wrapper around this sqlite crate but can't quite get the lifetime right, nor do I know what is wrong. Otherwise, I would've tried to make a minimal sample here. Anyway, this is what I've got:
use sqlite::{Connection, Statement};
static DB_FILE_NAME: &str = "./db.sqlite";
const TABLE_NAME: &str = "example_table";
const COLUMN_NAME: &str = "example_column";
pub struct SQLiteWrapper<'a> {
connection: &'a Connection,
statement: Statement<'a>,
}
impl<'a> SQLiteWrapper<'a> {
fn new() -> SQLiteWrapper<'a> {
let conn: &'a Connection = &sqlite::open(&DB_FILE_NAME).unwrap();
conn.execute(format!(
"CREATE TABLE {table_name} ({column_name} TEXT);",
table_name = TABLE_NAME,
column_name = COLUMN_NAME,
))
.unwrap_or_else(|err| println!("{:?}", err));
let statement = conn
.prepare(format!(
"INSERT INTO {table_name} VALUES ('?');",
table_name = COLUMN_NAME,
))
.unwrap();
SQLiteWrapper {
connection: conn,
statement,
}
}
fn insert_data(&mut self){
self.statement.bind(1, "some text").unwrap();
}
}
fn main() -> std::io::Result<()> {
SQLiteWrapper::new();
Ok(())
}
And I'm getting these errors:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:14:37
|
12 | impl<'a> SQLiteWrapper<'a> {
| -- lifetime `'a` defined here
13 | fn new() -> SQLiteWrapper<'a> {
14 | let conn: &'a Connection = &sqlite::open(&DB_FILE_NAME).unwrap();
| -------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
| |
| type annotation requires that borrow lasts for `'a`
...
34 | }
| - temporary value is freed at the end of this statement
error: aborting due to previous error
For more information about this error, try `rustc --explain E0716`.
Should I even be doing this in Rust? I know some OOP designs don't translate well unless you use a crate.
Either way, correct me if I'm wrong but I feel like this should be doable. I don't really understand what the problem is more than that the Connection struct seems to be freed instead of following 'a lifetime.
Is it because of how Connection::open() is implemented? Its signature is this:
pub fn open<T: AsRef<Path>>(path: T) -> Result<Connection> {
And from reading a few things (such as this blog) it seems as if though AsRef might be what is confusing me.
If anyone could help explain or point to what I need to look up that I'm not getting here, that'd be awesome!