gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:28:10 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com