Cloning variable inside of an "async move" block

You need to clone them in the closures, not in the async blocks that the closures return:

let make_svc = make_service_fn(move |socket: &AddrStream| {
    let collec = user_collection.clone();
    async move {
        Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
            let coll = collec.clone();
            async move {
                Ok::<_, Infallible>(match router(req, coll).await {
                    Ok(val) => val,
                    Err(_e) => Response::new(Body::empty()),
                })
            }
        }))
    }
});

This issue is that the closures might be called more than once: The outer is called for each connection, and the inner is called for each request on that connection. This means that the closures cannot move the value they own into the async block, because then they wouldn't have another value for the next time it's called.

1 Like