【发布时间】:2020-07-26 23:07:07
【问题描述】:
我正在使用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。有没有办法解决这个问题?
【问题讨论】:
-
您需要传递对
start_app的引用,还是可以传递所有权?如果您不能通过参考,您可以通过Rc或Arc吗? -
@loganfsmyth 你的意思是将
Database包裹在Arc中,并将所有权传递给Arc? -
@loganfsmyth 参考是非常可取的,因为
Database归其他人所有。 -
serve需要'static,因此它需要能够保证在服务器运行时不会删除数据库。如果其他东西拥有数据库的独占所有权,则无法保证。 -
@loganfsmyth 所以我应该通过
Arc<Database>并强制关闭以对其拥有所有权...?
标签: rust static borrow-checker object-lifetime rust-warp