Why cannot infer an appropriate lifetime for borrow expression?

I don't quite understand rust's lifecycle inference.
I shared a variable user_db for closure use, and in closure will call the handler function then borrow the variable, but this will error.
someone can explain to me why there are problems in this code and how to fix it.

use std::convert::Infallible;
use std::net::SocketAddr;
use hyper::{Body, Request, Response, Server, Client, Error};
use hyper::service::{make_service_fn, service_fn};
use log::{debug, info, trace};
use std::sync::{Arc, Mutex};
use slab::Slab;
use hyper::server::conn::AddrStream;
use pretty_env_logger::env_logger::builder;

type UserId = u64;
struct UserData;
type UserDb = Arc<Mutex<Slab<UserData>>>;
async fn main() {

    let user_db:UserDb = Arc::new(Mutex::new(Slab::new()));
    let in_addr = ([127, 0, 0, 1], 3001).into();

    let make_service = make_service_fn(move |_| {
        let data = user_db.clone();
        async move {
            Ok::<_, Infallible>(service_fn(move |req| {
                handler(req, &data)

    let server = Server::bind(&in_addr).serve(make_service);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);

async fn handler(_req: Request<Body>, data: &UserDb) -> Result<Response<Body>, Infallible> {
    Ok(Response::new("Hello, World".into()))

The handler must take the UserDb by value, so give it a clone of the Arc. This is because the future object the async fn generates is not allowed to contain borrows.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.