Capturing into a FnMut

Hello,

I'm trying to pass this data variable to the closure, it takes no parameters and it can't capture the data because it may not live long enough. I think I understand why this doesn't work, but I couldn't figure out a way to work around it.

#[tokio::main]
pub async fn run() {
    dotenv().ok();

    let connection = Database::connect(dotenv!("DATABASE_URL"))
        .await
        .map_err(|error| panic!("{error}"))
        .unwrap();

    let data = Arc::new(AppData { connection });

    AsyncScheduler::new()
        .every(1.hour())
        .run(|| async {
            some_other_function(&data.connection).await
        });

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(routes::build(&data).into_make_service())
        .await
        .unwrap();
}

I had a similar problem just a minute ago. Not sure if it helps in your case, but I did something like:

move || {
    let data = data.clone();
    async move {
        /* … */
    }
}

I had to clone within the closure but before the async block. Not sure if in your case it's the same. Note that the outer curly brackets are omitted in your example; you'd have to add them.

1 Like

Thanks !

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.