在下面的示例中,我使用 Arc 从请求处理程序引用服务器状态,但编译器将闭包设为FnOnce. 感觉就像我在做正确的事情,因为每个闭包都拥有对状态的强引用。为什么这不起作用?有什么选择可以使它工作?闭包之间的共享弧等其他问题表明类似这样的工作,但我正在制作每个闭包的克隆,如图所示,但仍然出现错误。
#![feature(async_closure)]
#[derive(Default, Debug)]
struct State {}
impl State {
pub async fn exists(&self, key: &str) -> bool {
true
}
pub async fn update(&self, key: &str) {}
}
#[tokio::main]
async fn main() {
use warp::Filter;
use std::sync::Arc;
let state: Arc<State> = Arc::default();
let api = warp::post()
.and(warp::path("/api"))
.and(warp::path::param::<String>().and_then({
let state = Arc::clone(&state);
async move |p: String| {
let x = state.exists(&p);
if x.await {
Ok(p)
} else {
Err(warp::reject::not_found())
}
}
})) …Run Code Online (Sandbox Code Playgroud)