Changing all values in a HashMap. Is this a good way?

Hello,

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);
		}
	}

}

This can be done more simply via:

impl MyStruct {
	pub fn reset_field2(&mut self) {
	    for value in self.field2hashmap.values_mut() {
	        *value = 0.0;
	    }
	}
}
10 Likes

Thank you so much. This is so much nicer!

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

impl MyStruct {
	pub fn reset_field2(&mut self) {
	    for (_, value) in &mut self.field2hashmap {
	        *value = 0.0;
	    }
	}
}

(Similar to how Vec and other collections does it, these implementations are also available via the .iter() and .iter_mut() methods, respectively.)

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.