-1

我正在 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

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

4

1 回答 1

1

第一次使用pagination作品,因为你移动它,第二次使用也会通过移动它来修复:

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

由于您要返回 a Future,因此它不能借用局部变量,因为它可以活得更久。

你可以移动pagination两次,因为PaginationQueryis Copy

于 2019-12-29T13:29:00.170 回答