Consider the following example:
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);
}
});
}
I'm getting the following error:
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
My intention is to only have do_something_expensive_returning_lots_of_data executed in a multithreaded fashion, then once it executes, have a single-threaded iterator with results of the calls so that I could then safely mutate h
. Is this possible with Rayon?