rust - 我如何使字符串比闭包体生命周期更长?

标签 rust rust-warp

我有这个代码:

.and_then(move |key: Option<String>| async {
    let pool = pool.clone();
    let key = key.as_ref().map(|s| &**s);

    match pool.get() {
        Ok(conn) => Ok(Session::from_key(conn, key)),
        Err(e) => {
            error!("Failed to get a db connection");
            Err(warp::reject::not_found())
        }
    }
})
.boxed()

我正在改编自 this example

但它给了我错误

lifetime may not live long enough

returning this value requires that `'1` must outlive `'2`

note: closure implements `Fn`, so references to captured variables can't escape the closurerustc
session.rs(131, 19): lifetime `'1` represents this closure's body
session.rs(131, 44): return type of closure is impl core::future::future::Future
session.rs(131, 46): returning this value requires that `'1` must outlive `'2`
async block may outlive the current function, but it borrows `key`, which is owned by the current function

may outlive borrowed value `key`rustc(E0373)
session.rs(131, 52): may outlive borrowed value `key`
session.rs(133, 23): `key` is borrowed here

我必须将 async 关键字添加到闭包中以避免错误:

the trait bound `std::result::Result<session::Session, warp::reject::Rejection>: core::future::future::Future` is not satisfied

the trait `core::future::future::Future` is not implemented for `std::result::Result<session::Session, warp::reject::Rejection>`

note: required because of the requirements on the impl of `futures_core::future::TryFuture` for `std::result::Result<session::Session, warp::reject::Rejection>`rustc(E0277)
session.rs(138, 10): the trait `core::future::future::Future` is not implemented for `std::result::Result<session::Session, warp::reject::Rejection>`

因此,现在看来闭包正在返回一个功能,但闭包已被释放,因此它会尝试在使用它之前释放 future ......关于如何补救这个问题有什么想法吗?

最佳答案

这个问题的主要理解是这个闭包的参数,key按值传递,String是一个拥有的字符串。所以当这个闭包运行时,key在这个闭包的栈帧中拥有,当闭包返回时,这个栈帧和它里面的所有东西都得到 drop()编辑。

key.as_ref()产生一个引用 key 的值在此堆栈框架中,rustc 不允许您从引用函数拥有的值的函数返回某些内容,因为一旦函数返回它们将不存在,这就是生命周期仅限于函数主体的原因。

要解决这个问题,您有 2 个选择:

  1. 通过 key通过引用这个函数key: Option<&str> , 然后是 Session可以返回堆栈,直到借用拥有的字符串。
  2. 创建 Session使用拥有的字符串,则该字符串由 session 拥有,并且可以按值传递(移动)而没有任何生命周期限制。

关于rust - 我如何使字符串比闭包体生命周期更长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62585051/

相关文章:

rust - 类型OnProduce = extern “C” fn不安全

rust - 使用 Rust,你如何在发布到 crate.io 之前执行平台测试?

rust - 如何使用 Warp 检查授权 header ?

http - 如何使用拒绝和问号运算符处理 Warp 中的错误?

rust - 如何将std::sync::mpsc::Sender <T>传递给warp中的处理程序?

rust - 如何重用扭曲中的路径?

rust - 如何在不移动向量的情况下迭代它

html - 紫杉醇错误–仅允许一个根html元素

types - 我应该使用什么类型声明来创建自己的HashMap contains方法?