在这样一个相当简单的情况下,我希望iter()
用人造丝 par_iter()
替换一个,但我没有这样做。
之前的代码:
indexes_to_increment
.iter()
.for_each(|x| self.some_data[*x as usize] += 1);`
这是人造丝修改的代码:
extern crate rayon;
use rayon::prelude::*;
fn main() {
let mut a = SomeStruct::new(vec![1, 0, 0, 1]);
a.add_factor_indexes(&vec![1, 2]);
println!("{:?}", a); // spits out "SomeStruct { some_data: [1, 1, 1, 1] }"
}
#[derive(Debug)]
struct SomeStruct {
some_data: Vec<u8>,
}
impl SomeStruct {
fn new(some_data: Vec<u8>) -> SomeStruct {
SomeStruct { some_data }
}
fn add_factor_indexes(&mut self, indexes_to_increment: &[u8]) {
//indexes_to_increment.iter().for_each(|x| self.some_data[*x as usize] += 1);
indexes_to_increment
.par_iter()
.for_each(|x| self.some_data[*x as usize] += 1);
}
}
(操场)
虽然我知道以下错误消息告诉我该怎么做,但此时我无法这样做。
error[E0387]: cannot borrow data mutably in a captured outer variable in an `Fn` closure
--> src/main.rs:23:27
|
23 | .for_each(|x| self.some_data[*x as usize] += 1);
| ^^^^^^^^^^^^^^
|
help: consider changing this closure to take self by mutable reference
--> src/main.rs:23:23
|
23 | .for_each(|x| self.some_data[*x as usize] += 1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如果我知道indexes_to_increment
向量 inadd_factor_indexes
只包含唯一u8
的 s 并且可以用一个集合替换,那会改变什么吗?