So I am trying to learn how to use Rayon, and this is a simple MWE of something I would like to do:
extern crate rayon; // 1.3.0
use rayon::prelude::*;
fn main(){
let mut v = vec![0,100];
v
.par_iter()
.enumerate()
.for_each
(|(i,_)|
{
v[i] = i;
}
);
}
When I do this, I get the error:
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow `v` as mutable, as it is a captured variable in a `Fn` closure
--> src/main.rs:13:13
|
13 | v[i] = i;
| ^ cannot borrow as mutable
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:11:6
|
7 | v
| - immutable borrow occurs here
...
10 | .for_each
| -------- immutable borrow later used by call
11 | (|(i,_)|
| ^^^^^^^ mutable borrow occurs here
12 | {
13 | v[i] = i;
| - second borrow occurs due to use of `v` in closure
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0502, E0596.
For more information about an error, try `rustc --explain E0502`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
And basically I can't figure out how to make this operation possible using Rayon. Hope someone can help out.
You would have to zip the iterators together like this. You can only use the vectors directly if the vector is not modified for the entire parallel operation.
fn main(){
let mut v = vec![0; 100];
let mut u = vec![0; 100];
v.par_iter_mut()
.zip(u.par_iter_mut())
.enumerate()
.for_each(|(i, (v_ptr, u_ptr))| {
// This uses the closure parameter instead.
*v_ptr = i;
*u_ptr = 2*i;
});
println!("{:?}", v);
println!("{:?}", u);
}