借入的价值使用期限不足,由于在封包E0597中的使用而移动 [英] Borrowed value does not live long enough, moved due to use in closure E0597

查看:86
本文介绍了借入的价值使用期限不足,由于在封包E0597中的使用而移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Actix-Web上迈出第一步。但这会导致我出错

I am taking my first steps on Actix-Web. But this closure causes me errors

#[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

我不明白为什么可以再次使用分页值。

I don't understand why I can't use the paging value a second time. What is the problem here?

推荐答案

第一次使用分页之所以有效,是因为您移动了它,第二种用法也可以通过移动它来解决:

The first use of pagination works because you move it, the second use would be fixed by also moving it:

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

由于您返回的是 Future ,因此不能可以使用局部变量,因为它可以生存更长的时间。

Since you are returning a Future, it cannot borrow local variables, as it could live longer.

您可以移动分页两次,因为 PaginationQuery Copy

You can move pagination twice because PaginationQuery is Copy.

这篇关于借入的价值使用期限不足,由于在封包E0597中的使用而移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆