rust - 闭合体的生命周期与传递给它的值之间不匹配

标签 rust closures lifetime ownership rust-warp

我有以下情况:

let rpc_endpoint: String =
        matches.value_of("rpc_endpoint").unwrap().to_owned();

/* later on... */

let create_order_route = warp::path!("book" / String)
        .and(warp::post())
        .and(warp::body::json())
        .and(warp::any().map(move || create_order_state.clone()))
        .and(warp::any().map(move || rpc_endpoint.as_str()))
        .and_then(handler::create_order_handler);*/
编译器提示一个潜在的生命周期问题:
error: lifetime may not live long enough
   --> src/main.rs:153:38
    |
153 |         .and(warp::any().map(move || rpc_endpoint.as_str()))
    |                              ------- ^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
    |                              |     |
    |                              |     return type of closure is &'2 str
    |                              lifetime `'1` represents this closure's body
    |
    = note: closure implements `Fn`, so references to captured variables can't escape the closure
尚不清楚rpc_endpoint.as_str()是否会超过闭包,因为所有引用都是Copy

最佳答案

rpc_endpointString,因此它拥有其内容。
当您像这样使用move时:

move || rpc_endpoint.as_str()
捕获变量的所有权(在本例中为rpc_endpoint)被移至闭包中。
因此,现在您有了一个闭包,该闭包将返回对闭包内现在是局部变量的引用。一旦关闭返回,rpc_endpoint将被删除,因此您当然不能返回对其的引用。
相反,请事先获取引用并在闭包中使用该引用:
let rpc_endpoint_ref = rpc_endpoint.as_str();

let create_order_route = warp::path!("book" / String)
        .and(warp::post())
        .and(warp::body::json())
        .and(warp::any().map(move || create_order_state.clone()))
        .and(warp::any().map(move || rpc_endpoint_ref))
        .and_then(handler::create_order_handler);
只要rpc_endpoint超过对它的引用,那将起作用。

关于rust - 闭合体的生命周期与传递给它的值之间不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65986510/

相关文章:

reference - 如何使用 `AsRef` 参数?

rust - 有没有办法将结构体的属性指定为函数的参数?

rust - 我可以接受两个&str参数并返回一个或另一个吗?

rust - 如何分配切片范围? [复制]

rust - 如何在编译时创建静态字符串

python - 闭包如何在 runpy 中工作?

c# - 使用委托(delegate)对列表进行问题排序

javascript - 即使组件被销毁,异步进程是否按预期完成

compiler-errors - 尽管受到限制,但值(value)还不够长

rust - StreamExt .scan()方法上的“expected bound lifetime parameter, found concrete lifetime”