考虑以下示例:
use rayon::prelude::*;
fn do_something_expensive_returning_lots_of_data(x: u32) -> u32 {
x
}
fn main() {
let very_large_array = [1, 2, 3, 4];
let mut h = std::collections::HashSet::new();
very_large_array.par_iter().for_each({
|x| {
let c = do_something_expensive_returning_lots_of_data(*x);
h.insert(c);
}
});
}
我收到以下错误:
error[E0596]: cannot borrow `h` as mutable, as it is a captured variable in a `Fn` closure
--> src/main.rs:13:13
|
13 | h.insert(c);
| ^ cannot borrow as mutable
我的意图是只让 do_something_expensive_returning_lots_of_data 以多线程方式执行,然后一旦执行,就有一个带有调用结果的单线程迭代器,这样我就可以安全地 mutate h
。人造丝可以吗?