Borrow check in `tokio::task::spawn`

A little bit new to rust.

I want to build a http server with hyper, tokio and other crates. And below is a part of my code:

    pub async fn run(
        &self,
        host: Option<String>,
        port: Option<u32>,
    ) -> Result<(), Box<dyn Error>> {
        let addr = format!(
            "{}:{}",
            host.unwrap_or(self.config.host.clone()),
            port.unwrap_or(self.config.port)
        );

        if self.config.load_dotenv{
            println!("try to load .env");
        }
        
        let server = TcpListener::bind(&addr).await?;

        println!("Listening on : {}", addr);

        loop {
            let (stream, _) = server.accept().await?;

            let io = TokioIo::new(stream);
            tokio::task::spawn(async move {
                if let Err(err) = ConnectionBuilder::new()
                    .serve_connection(
                        io,
                        hyper::service::service_fn(|request| async {
                            self.process_request(request).await
                        }),
                    )
                    .await
                {
                    println!("Error serving connection: {:?}", err);
                }
            });
        }
    }

I know the problem lies in this line of code: self.process_request(request).await, i tried using 'Arc', but there are still new issues.

Another way I can think of is to put the process_request method outside, but this is not solving the problem,it just avoids

Can anyone help me to work this out ?

Could you elaborate what you tried? Did you try self: Arc<Self>, plus let this = Arc::clone(&self) in the loop and usage of this.process_request?

1 Like

I forgot to mark the type of self as Arc<Self> , the rest is the same as you . Thx a lot !

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.