Home > OS >  How to avoid multiple Arc::clone when dealing with multiple closures?
How to avoid multiple Arc::clone when dealing with multiple closures?

Time:12-15

    let store = Arc::new(DashMap::new());
    tokio::spawn({
        let store = Arc::clone(&store);
        async move {
            stream::iter(vec![17, 19]).for_each(move |x| {
                let store = Arc::clone(&store);
                async move {
                    store.insert(x, x);
                }
            })
        }
    });

I have to clone two times and do it behind async blocks just to have an ability to use it once deep in the closures. Are there any ways to simplify such code?

CodePudding user response:

Just leave them out, the only necessary clone is the one inside of iter because each iteration needs it's own Arc.

This works unless there is some requirements not mentioned in the question.

    let store = Arc::new(DashMap::new());
    tokio::spawn(async move {
        stream::iter(vec![17, 19]).for_each(move |x| {
            let store = Arc::clone(&store);
            async move {
                store.insert(x, x);
            }
        })
    });

If you can move the insert outside of the innermost async move block you can get rid of even that clone.

  • Related