How to solve this lifetime problem?

:sob: can someone help me with this? I've met this problem a lot of times.

    //in lib
    pub async fn run(&'static self, addr: String) -> Result<(), Box<dyn Error>> {
        let listener = TcpListener::bind("127.0.0.1:8080").await?;
        loop {
            let (socket, _) = listener.accept().await?;
            tokio::spawn(handle_connection(&self, socket));
        }
    }
//in main
App::new().run("".to_string());
// complains 
//temporary value dropped while borrowed 
//creates a temporary which is freed while still in use

Why do you need the 'static lifetime for self? That tells the compiler self needs to be valid beyond the end of main, which is causing your compile error.

1 Like

Hi, I try not using static but in the handle function would complains, and I don't want to copy the app each time in the loop.

Consider passing around Arc<App> instead of &App.

pub async fn run(self: Arc<Self>, addr: String) -> Result<(), Box<dyn Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    loop {
        let app = self.clone();
        let (socket, _) = listener.accept().await?;
        tokio::spawn(handle_connection(app, socket));
    }
}

in main:

//in main
Arc::new(App::new()).run("".to_string());

(You'll probably also need to change handle_connection to take Arc.)

Cloning the Arc is cheap, like copying a reference. The new Arc will still point to the same, shared App value.

Hi, I tried your advice and I can complie, the only problem is when i run it, I get a stack overflow :joy:

When the compiler tells you to add 'static don't listen to it. It's almost always a wrong, misleading suggestion.

When compiler says it wants 'static, it tries to say that all temporary references are forbidden. 'static just happens to be the only case of a reference that isn't temporary, but in practice it's a useless solution, because almost nothing in real programs can be static (i.e. a constant or leaked memory). The real solution is to use self-contained/owned types, Arc, or a copy of the data instead.

Compiler bug:

https://github.com/rust-lang/rust/issues/69350

4 Likes

Thank you!

I was long annoyed by that suggestion, thanks for bringing it up! (it's only now that I see the issue on GitHub.)

Any potential recursion or really big arrays in your code?

yes it's my fault, I arranged a very big array in my code which causes the problem

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.