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

我有这个代码:

.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 拥有,并且可以按值传递(移动)而没有任何生命周期限制。

https://stackoverflow.com/questions/62585051/

相关文章:

java - SonarQube Scanner - 插件下载之间的长时间停顿

string - 将字符串拆分为最少数量的字符串,其中每个字母重复奇数次

javascript - 如何使用 React 在客户端裁剪图像而不丢失分辨率

javascript - Angular ngrx : TypeError: Cannot free

python - DBSCAN 聚类甚至无法处理 40k 数据,但可以使用 python 和 skl

html - 如何在选择下拉菜单上设置 Font Awesome 图标?

ios - UIView 作为@EnvironmentObject 的订阅者

vue.js - 当对象没有(可识别的)变化时触发 Vue 监视

r - 在 Windows 上安装 odbc R 包时出现问题

java - 将内部 HashMap 类型强制转换为 Map