Rust 借来的价值寿命不够长,由于在E0597中使用而移动
我在Actix Web上迈出了第一步。但是这个闭包导致了我的错误Rust 借来的价值寿命不够长,由于在E0597中使用而移动,rust,closures,actix-web,Rust,Closures,Actix Web,我在Actix Web上迈出了第一步。但是这个闭包导致了我的错误 #[derive(Deserialize, Serialize, Debug, Copy, Clone)] pub struct PaginationQuery { pub limit: Option<u32>, pub offset: Option<u32>, } pub fn get_all_trainings_2( query: web::Query<Paginatio
#[derive(Deserialize, Serialize, Debug, Copy, Clone)]
pub struct PaginationQuery {
pub limit: Option<u32>,
pub offset: Option<u32>,
}
pub fn get_all_trainings_2(
query: web::Query<PaginationQuery>,
pool: web::Data<Pool>,
) -> impl Future<Item = HttpResponse, Error = Error> {
let mut pagination = query.0;
// Thread Blocking
web::block(move || database::get_exercises(pool, pagination)).then(|res| {
match res {
Ok((trainings_list, total)) => {
// let mut list: Vec<TrainingsResponse> = Vec::new();
let list: Vec<TrainingsResponse> = trainings_list
.into_iter()
.map(|tr| TrainingsResponse::from(tr))
.collect();
Ok(HttpResponse::Ok().json(ListResult {
offset: pagination.offset.unwrap_or(0),
total: total as u32,
items: list,
}))
}
Err(_) => Ok(HttpResponse::InternalServerError().into()),
}
})
}
#[派生(反序列化、序列化、调试、复制、克隆)]
发布结构分页查询{
发布限制:选项,
发布偏移量:选项,
}
酒吧fn获得所有培训2(
查询:web::query,
池:web::Data,
)->impl未来{
让mut pagination=query.0;
//线程阻塞
web::block(move | | database::get|u练习(pool,pagination))。然后(| res |{
匹配资源{
正常((培训列表,总计))=>{
//让mut list:Vec=Vec::new();
let list:Vec=trainings\u list
.into_iter()
.map(| tr | trainingresponse::from(tr))
.收集();
Ok(HttpResponse::Ok().json(ListResult{
偏移:分页。偏移。展开或(0),
总计:总计为u32,
项目:清单,
}))
}
Err()=>Ok(HttpResponse::InternalServerError().into()),
}
})
}
错误:
错误[E0597]:`pagination`的寿命不够长
-->src\handler.rs:66:29
|
51 |)->实现未来{
|-----------------------------------------------------不透明类型要求为`'static借用`'pagination``
...
55 | web::block(移动| |数据库::获取|练习(池、分页))。然后(| res |{
|----此处捕获的值
...
66 |偏移:分页。偏移。展开或(0),
|^^^^^^^^^^^^^^^^借来的价值寿命不够长
...
74 | }
|-“分页”在仍然被借用的时候掉在了这里
我不明白为什么我不能再次使用分页值。这里有什么问题?第一次使用
分页
有效,因为您移动了它,第二次使用也会通过移动它来修复:
web::block(move || database::get_exercises(pool, pagination)).then(move |res| { … })
// ^^^^ ^^^^
由于您返回的是一个未来
,因此它不能借用局部变量,因为它可能寿命更长
你可以移动
pagination
两次,因为PaginationQuery
是Copy
我不知道web::block
是什么,但它看起来像是返回了未来,因此不能借用局部变量。pagination
的第一次使用有效,因为你移动了它,第二次使用可能会被als修复o移动它。@mcarton感谢您的回答web::block(Actix web)并不重要,重要的是在线程池中执行代码(Diesel不支持tokio,所以我们必须在单独的线程中运行)。我不明白如何进行第二步。您能举例说明吗?