Please bear with me as I'm fairly new to Rust. This is one of my first toy projects using the language.
I'm playing with a webapp project where I use SQLite to store some data and Axum as the application framework.To share the DB connection between different routes, I use Axum's Extension
. The problem I'm running into is that I get an error about how the conn object doesn't live long enough to be borrowed into Extension.
Consider the following MWE:
Cargo.toml
[package]
name = "mwe_axum_tokio_sqlite"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7.5"
tokio = { version = "1.37.0", features = ["full"] }
tokio-rusqlite = "0.5.1"
main.rs
use axum::extract::{Extension};
use tokio::net::TcpListener;
use tokio_rusqlite::{Connection};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let conn = Connection::open_in_memory().await.expect("Failed to open db.");
//... init db
let app = axum::Router::new()
//.. routes
.layer(Extension(conn));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app).await?;
Ok(())
}
When compiled, this produces the following error
error[E0597]: `conn` does not live long enough
--> src/main.rs:12:24
|
7 | let conn = Connection::open_in_memory().await.expect("Failed to open db.");
| ---- binding `conn` declared here
8 | //... init db
9 | let app = axum::Router::new()
| _______________-
10 | | //.. routes
11 | | //.route("/", get(index))
12 | | .layer(Extension(&conn));
| |________________________^^^^^_- argument requires that `conn` is borrowed for `'static`
| |
| borrowed value does not live long enough
...
17 | }
| - `conn` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
I get the gist of it, that conn
is dropped at the end of main, whereasExtension
requires it to have static lifetime, but I don't know what to do about it. I'd appreciate any help on resolving this.