Passing Arc to async mut closure

Hi there,
I feel like I'm totally stuck: I want to pass Arc to async closure and I have no idea what's wrong with it. I used example code from https://docs.rs/futures/0.3.5/futures/stream/trait.StreamExt.html#method.for_each_concurrent and tweaked it a bit.

use futures::channel::oneshot;
use futures::stream::{self, StreamExt};
use std::sync::Arc;

fn main() {
    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    let (tx3, rx3) = oneshot::channel();

    let a = Arc::new(1337);

    let fut = stream::iter(vec![rx1, rx2, rx3]).for_each_concurrent(/* limit */ 2, {
        let bruh = a.clone();
        |rx| async move {
            bruh;
            rx.await.unwrap();
        }
    });
    tx1.send(()).unwrap();
    tx2.send(()).unwrap();
    tx3.send(()).unwrap();
}

error[E0507]: cannot move out of `bruh`, a captured variable in an `FnMut` closure

Thanks!

async move block takes and destroys bruh. The closure has only one copy of bruh, but will be called multiple times, and every time a new async move will want one more copy to destroy.

You must clone yet again inside the closure, but before async move {} block.

1 Like

Oh I didn't notice that async move {} != closure's body in general, thank you very much!

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.