Reputation: 118630
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 JoinHandle
s 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?
Upvotes: 2
Views: 1445
Reputation: 215107
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.
Upvotes: 5