【问题标题】:cannot move out of `*h` which is behind a shared reference不能移出共享引用后面的 `*h`
【发布时间】:2019-11-08 01:19:02
【问题描述】:

我正在尝试使用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 向我提供了对JoinHandles 的引用,这应该可以正常工作,但似乎我没有。以下代码工作正常:

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

我该如何做同样的事情,但使用for_each 或类似的东西?

【问题讨论】:

    标签: rust


    【解决方案1】:

    您需要into_iter instead of iter。使用iter,您只能获得项目的引用,而join 的签名为pub fn join(self) -&gt; Result&lt;T&gt;,需要拥有的数据作为参数:

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

    应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-27
      • 2020-09-11
      • 1970-01-01
      • 2020-02-12
      • 2021-12-02
      • 1970-01-01
      • 2010-11-13
      相关资源
      最近更新 更多