I am very new to Rust. Will appreciate your feedback.
I need to define a method that resets a HashMap within a struct by setting value for every key in the hashmap to zero. I struggled with multiple borrows to get it working. But finally I came up with this (based on reading various posts on the internet), which works. Is this a good way? Do you think there is a better way in your opinion that you would use instead of this? Thank you.
#[derive(Debug)]
pub struct MyStruct {
pub field1: Vec<u8>,
pub field2hashmap: HashMap<u8,f64>
}
impl MyStruct {
/// Set all the value to 0.0
pub fn reset_field2(&mut self) {
let oppindices = self.field2hashmap.keys()
.map(|keyref| *keyref)
.collect::<Vec<u8>>();
for oppidx in oppindices {
self.field2hashmap.entry(oppidx)
.and_modify(|v| *v = 0.0);
}
}
}
Another often useful thing to be aware of when using HashMap is the IntoIterator implementations for &HashMap<K, V> and &mut HashMap<K, V> which hand out (&K, &V) items or (&K, &mut V) items, respectively. Using the mutable-reference one allows you to write the same code as