rust - 无法移出共享引用后面的 `*h`

标签 rust

我正在尝试使用 for_eachJoinHandle 向量上调用 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/

相关文章:

rust - 如何使用消耗该成员本身的成员方法替换结构成员?

rust - 如何将返回值的生命周期设置为我移入其中的变量的生命周期?

Rust,如何执行基本的递归异步?

iterator - 为什么有两种迭代向量的方法,IntoIterator 和 Iter?

rust - 如何使用依赖的依赖类型?

rust - 是否可以声明 2 个相互依赖的静态可变变量?

rust - 如何静音 `rustc` 关于要链接到哪些 native 工件的注释?

http - 如何使用 select.rs 从 HTML 文档中提取 "href"属性?

rust - 如何从标准输入读取操作系统兼容的字符串?

rust - 如何在 Rust 中将十六进制字符串转换为 float ?