我已将应用程序状态定义为具有生命周期参数,如下所示:
pub struct ServiceState<'a> {
pub db: sync::Mutex<Database<'a>>,
}
impl<'a> ServiceState<'a> {
pub async fn new() -> Result<ServiceState<'a>, Error> {
let db = database::ConnectionPool::new(CONFIGURATION).await?;
Ok(ServiceState {
db: sync::Mutex::new(db),
})
}
}
并按预期将其传递给actix服务器,代码如下:
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
let state = model::ServiceState::new();
let uri = connection::uri();
let data = web::Data::new(state);
let mut server = HttpServer::new(move || {
App::new()
.app_data(data.clone())
.configure(routes::configuration)
});
// ... more code ...
server.run().await
}
当我尝试访问存储在路由中的应用程序状态中的数据库时,请参见下文:
pub async fn do_stuff(
state: web::Data<model::ServiceState<'_>>,
json: web::Json<model::RequestBody>,
) -> HttpResponse {
let _data = model::RequestBody::from(json);
// MutexGuard<'_, Database<'_>> is just to show what types are being used
let db: MutexGuard<'_, Database<'_>> = state.db.lock().unwrap();
let _client = db.client().await.unwrap();
// ... would be other logic here but commented out to isolate error
HttpResponse::Ok().finish()
}
我收到以下错误:
error[E0597]: `state` does not live long enough
--> src/handler/verification.rs:12:48
|
8 | state: web::Data<model::ServiceState<'_>>,
| ----- lifetime `'1` appears in the type of `state`
...
12 | let mut db: MutexGuard<'_, Database<'_>> = state.db.lock().unwrap();
| ^^^^^----------
| |
| borrowed value does not live long enough
| argument requires that `state` is borrowed for `'1`
...
32 | }
| - `state` dropped here while still borrowed
error[E0597]: `db` does not live long enough
--> src/handler/verification.rs:13:19
|
8 | state: web::Data<model::ServiceState<'_>>,
| ----- lifetime `'1` appears in the type of `state`
...
13 | let _client = db.client().await.unwrap();
| ^^---------
| |
| borrowed value does not live long enough
| argument requires that `db` is borrowed for `'1`
...
32 | }
| - `db` dropped here while still borrowed
我一直在戳戳这个问题,尝试不同的生命周期,指定一个人应该比另一个人活得更长,等等都无济于事。我想我缺少对为什么会发生此错误消息的具体理解。我的思考过程是客户端和数据库都是在函数内部借用的,所以我很困惑为什么当函数结束时它们被删除应该是一个问题。
我会注意到我的代码(比这个例子大)在我向应用程序状态引入生命周期参数之前都运行良好,所以我假设我只是没有提供编译器之前没有提供的一些生命周期参数。
我希望当前的示例足以至少对出了什么问题有所了解。
任何帮助将不胜感激,我对 rust/actix 还很陌生,并且努力让这个(看起来应该是相当常见和简单的用例)工作。