0

I'm struggling getting hold of my shared data from within the closure that try_for_each_concurrent calls:

use futures::channel::oneshot;
use std::sync::Arc;

use futures::stream::{self, StreamExt, TryStreamExt};

fn main() {
    let arc_val = Arc::new(5);

    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    let (_tx3, rx3) = oneshot::channel();

    let stream = stream::iter(vec![rx1, rx2, rx3]);
    let future =
        stream
            .map(Ok)
            .try_for_each_concurrent(5, |channels: oneshot::Receiver<u32>| async move {
                let arc_ref = Arc::clone(&arc_val);
                use_arc(arc_ref).await
            });
}

async fn use_arc(arc_ref: Arc<u32>) -> Result<(), String> {
    println!("Value {}", arc_ref);
    Ok(())
}

(Playground)

Errors:

error[E0507]: cannot move out of `arc_val`, a captured variable in an `FnMut` closure
  --> src/main.rs:17:87
   |
7  |       let arc_val = Arc::new(5);
   |           ------- captured outer variable
...
17 |               .try_for_each_concurrent(5, |channels: oneshot::Receiver<u32>| async move {
   |  _______________________________________________________________________________________^
18 | |                 let arc_ref = Arc::clone(&arc_val);
   | |                                           -------
   | |                                           |
   | |                                           move occurs because `arc_val` has type `std::sync::Arc<u32>`, which does not implement the `Copy` trait
   | |                                           move occurs due to use in generator
19 | |                 use_arc(arc_ref).await
20 | |             });
   | |_____________^ move out of `arc_val` occurs here

The error that is occurring is a generalised version of what I'm actually experiencing, but solving that should solve my problem.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Simon
  • 69
  • 1
  • 6
  • It looks like your question might be answered by the answers of [Is there another option to share an Arc in multiple closures besides cloning it before each closure?](https://stackoverflow.com/q/31360003/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Mar 10 '20 at 16:59
  • [The duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1ad1b84647367d59d2469e6152048b94). – Shepmaster Mar 10 '20 at 17:00

0 Answers0