我正在使用seanmonstar/warp来构建我的休息服务并面临与生命周期相关的问题。这是我的应用程序启动代码的样子:
struct MyModelStruct {
//...
}
struct Database {
//...
}
impl Database {
fn connect(/* ommited */) -> Database {
//...
}
}
fn start_app(db: &Database) -> () {
let route = warp::post()
.and(warp::path!("action" / u32))
.and(warp::body::json::<MyModelSctruct>())
.map(|_, _| {
//use db
})
warp::serve(route).run(/* address */);
}
我得到了错误:
error[E0621]: explicit lifetime required in the type of `db`
--> src/application.rs:69:5
|
46 | fn start_app(db: &Database) -> (){
| -------- help: add explicit lifetime `'static` to the type of `db`: `&'static db::Database`
...
69 | warp::serve(route);
| ^^^^^^^^^^^ lifetime `'static` required
这是因为warp::serve
函数定义为
/// Create a `Server` with the provided `Filter`.
pub fn serve<F>(filter: F) -> Server<F>
where
F: Filter + Clone + Send + Sync + 'static,
F::Extract: Reply,
F::Error: IsReject,
{
Server {
pipeline: false,
filter,
}
}
所以'static
生命周期是明确要求的。问题是它被用作
let db = Database::connect(...);
start_app(&db);
所以 db 的生命周期不是static
. 有没有办法解决这个问题?