我正在尝试使用 for_each
在 JoinHandle
向量上调用 join。我收到此错误:
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
据我所知,如果 for_each
为我提供了对 JoinHandle
的引用,这应该可以正常工作,但似乎我没有。下面的代码工作正常:
for h in threads {
h.join().unwrap();
}
我如何做同样的事情,但使用 for_each
或类似的东西?
最佳答案
您需要 into_iter
instead of iter
。与iter
您只能获得项目的引用,而 join
签名为 pub fn join(self) -> Result<T>
它需要拥有的数据作为参数:
threads.into_iter().for_each(|h| { h.join().unwrap(); });
应该可以。
关于rust - 无法移出共享引用后面的 `*h`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759086/