Why does the following code raises an error[E0499]: cannot borrow
*nested as mutable more than once at a time
fn insert<'a>(
nested: &'a mut HashMap<K1, HashMap<K2, V>>,
first: &'_ K1,
second: K2,
value: V,
) -> &'a V {
let inner = if let Some(x) = nested.get_mut(first) {
x
} else {
nested.entry(first.to_owned()).or_default()
};
inner.entry(second).or_insert(value)
}
The two mutable borrows (get_mut
and entry
on nested
) are happening sequentially.
No closure de-sugaring involved either, like in Borrow mutably, then borrow mutably again
P.S. I'm trying to prevent an extra clone first.to_owned
when entry exists, not sure if it is worth it.