Here's a MWE:
use std::collections::HashMap;
use rayon::prelude::*;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Car {
year: u32,
make: String,
model: String
}
fn main() {
let cars: Vec<Car> = vec![
Car {
year: 2021, make: "Honda".to_string(), model: "Accord".to_string()
},
Car {
year: 1995, make: "Ford".to_string(), model: "F-150".to_string()
},
Car {
year: 2021, make: "Honda".to_string(), model: "Civic".to_string()
},
Car {
year: 2000, make: "Ford".to_string(), model: "Mustang".to_string()
},
Car {
year: 1995, make: "Peugeot".to_string(), model: "405".to_string()
}
];
let mut siblings: HashMap<Car, Vec<Car>> = HashMap::new();
cars.iter()
.enumerate()
.for_each(|(i, car)| {
for j in i+1..cars.len() {
if car.make == cars[j].make {
if siblings.contains_key(&car) {
let v = siblings.get_mut(&car).unwrap();
v.push(cars[j].clone())
} else {
siblings.insert(car.clone(), vec![cars[j].clone()]);
}
}
}
});
println!("{:#?}", siblings);
}
This works just fine. However, changing iter() to par_iter() results in an error which tells me that siblings cannot be borrowed as mutable since it's captured in a 'Fn' closure. I'm very inexperienced with Rust and some searching yielded some information about Arc and Mutex but I haven't figured out how to get that to work.
I would greatly appreciate some guidance as to how to parallelize the iterator (and eventually the inner loop as well
). Any other feedback to improve this bit of code is also very welcome!!