0

I have the following situation:

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

The compiler complains about a potential lifetime issue:

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

Is it not clear that rpc_endpoint.as_str() will outlive the closure, as all references are Copy?


sporejack
  • 71
  • 1
  • 6

1 Answers1

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.

harmic
  • 28,606
  • 5
  • 67
  • 91