我有以下情况:
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_endpoint
是String
,因此它拥有其内容。
当您像这样使用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/