How to clone a struct that contains async functions?

I have a struct that I want to able to clone, Even though Clone is derived without any error, It fails when I try to call .clone() method.

My use case is being able to spawn without consuming self (I have tried borrowing but that lead to a lot of problems that I couldn't fix), I have also tried Arc but couldn't get it to work.

I'm new to Rust, So any help would be much appreciated!

Playground

#[derive(Clone)]
struct FuncStore<F>
where
    F: std::future::Future + Send + 'static,
{
    funcs: Vec<fn() -> F>,
}

impl<F> FuncStore<F>
where
    F: std::future::Future + Send + 'static,
{
    async fn spawn(self) {
        for func in self.funcs.into_iter() {
            tokio::spawn(async move {
                func().await;
            });
        }
    }
}

derive(Clone) will include a where F: Clone bound on the impl it generates, because it's very simplistic and doesn't look into the struct's definition to see whether this bound is actually needed. This is issue #26925.

The solution is to write a manual Clone impl without that bound:

impl<F> Clone for FuncStore<F>
where
    F: std::future::Future + Send + 'static,
{
    fn clone(&self) -> Self {
        Self { funcs: self.funcs.clone() }
    }
}
2 Likes

Since function pointers(fn() -> T) are Copy, you can copy it out from its shared reference.

for &func in &self.funcs {
    tokio::spawn(async move {
        func().await;
    });
}
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.