0

我有以下情况:

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


4

1 回答 1

2

rpc_endpoint is a String, so it owns its content.

When you use move like this:

move || rpc_endpoint.as_str()

ownership of the captured variables (in this case, rpc_endpoint) is moved into the closure.

So, now you have a closure which is returning a reference to what is now a local variable within the closure. As soon as the closure returns, rpc_endpoint will be dropped, so you certainly cannot return a reference to it.

Instead, take the reference beforehand and use that within the closure:

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);

That will work as long as rpc_endpoint outlasts the reference to it.

于 2021-02-01T03:12:33.623 回答