I would like to remove a (key, value)
from an ordered hashmap depending on some property regarding the value.
I wrote the following minimal example:
use std::collections::BTreeMap;
pub fn remove_if42(map: &mut BTreeMap<String, u32>) -> Option<u32> {
// Get the first element (minimum) from the ordered hash
let (key, value) = map.iter_mut().next()?;
if *value == 42 {
map.remove(key);
}
Some(*value)
}
I can read the value, but when I ask to delete the key, I get a borrowing error:
error[E0499]: cannot borrow `*map` as mutable more than once at a time
--> src/lib.rs:8:9
|
5 | let (key, value) = map.iter_mut().next()?;
| --- first mutable borrow occurs here
...
8 | map.remove(key);
| ^^^ --- first borrow later used here
| |
| second mutable borrow occurs here