E0499: Iterating over self.hashmap and calling mut method on self

Hey,

Is there any idiomatic way of solving the following error: Rust Playground Example

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:26:13
   |
25 |         for (_,v) in self.map.iter_mut() {
   |                      -------------------
   |                      |
   |                      first mutable borrow occurs here
   |                      first borrow later used here
26 |             self.flag_value(v);
   |             ^^^^ second mutable borrow occurs here

This a reduced example of a problem I recently ran into. The check_values() function is meant to be called in numerous location throughout the code.

I'm iterating a set of values in a hashmap and when some value matches a condition (not in the example) i would like to add it to a flagged list to be processed at a later stage as well as update the existing value in the map.

I've managed to work around the problem, by temporarily moving the hashmap to a temp variable using std::mem::replace and then back again once the loop is done.

That being said, I was wondering whether there was a "cleaner" and/or more idiomatic way of handling this scenario?

Do not make your flag_value() function take the entirety of self. Instead, borrow only the fields from self which are actually needed for performing whatever action flag_value() wants to perform, and pass those explicitly to the function.

1 Like

Seems to work. Thanks!