【问题标题】:Borrowed value does not live long enough, moved due to use in closure E0597借来的价值不够长,由于在关闭时使用而移动 E0597
【发布时间】:2023-03-28 20:21:01
【问题描述】:

我正在 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<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()),
        }
    })
}

错误:

error[E0597]: `pagination` does not live long enough
  --> src\handler.rs:66:29
   |
51 | ) -> impl Future<Item = HttpResponse, Error = Error> {
   |      ----------------------------------------------- opaque type requires that `pagination` is borrowed for `'static`
...
55 |     web::block(move || database::get_exercises(pool, pagination)).then(|res| {
   |                                                                        ----- value captured here
...
66 |                     offset: pagination.offset.unwrap_or(0),
   |                             ^^^^^^^^^^ borrowed value does not live long enough
...
74 | }
   | - `pagination` dropped here while still borrowed

我不明白为什么我不能第二次使用分页值。这里有什么问题?

【问题讨论】:

  • 我不知道web::block是什么,但看起来它返回了一个未来,因此不能借用局部变量。第一次使用 pagination 有效,因为您移动它,第二次使用也可能通过移动它来修复。
  • @mcarton 谢谢你的回答 web :: block (Actix-Web) 不重要是在线程池中执行代码(Diesel不支持tokio,所以我们必须在单独的线程。)docs.rs/actix-web/1.0.5/actix_web/web/fn.block.html我不明白我如何才能采取第二步。你能举个例子吗?

标签: rust closures actix-web


【解决方案1】:

pagination 第一次使用是因为你移动了它,第二次使用也可以通过移动它来修复:

web::block(move || database::get_exercises(pool, pagination)).then(move |res| { … })
//         ^^^^                                                    ^^^^

由于您返回的是Future,因此它不能借用局部变量,因为它的寿命可能更长。

您可以移动 pagination 两次,因为 PaginationQueryCopy

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2015-04-12
    • 2014-12-26
    • 2021-12-22
    相关资源
    最近更新 更多