2

I'm trying to call join on a vector of JoinHandle, using for_each. I get this error:

let mut threads = vec![];
...
threads.iter().for_each(|h| h.join().unwrap());

error[E0507]: cannot move out of `*h` which is behind a shared reference
  --> src/main.rs:41:33
   |
41 |     threads.iter().for_each(|h| h.join().unwrap());
   |                                 ^ move occurs because `*h` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait

As far as I can tell, this should work fine if I were given references to the JoinHandles by for_each, but it seems I'm not. The following code works fine:

for h in threads {
    h.join().unwrap();
}

How do I do the same but using for_each or something similar to it?

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

1 Answers1

4

You need into_iter instead of iter. With iter you only get references of items, while join has a signature as pub fn join(self) -> Result<T> which requires owned data as parameter:

threads.into_iter().for_each(|h| { h.join().unwrap(); });

should work.

Psidom
  • 209,562
  • 33
  • 339
  • 356