Compiler/Borrow Checker bug?


In code like this

if let Some(v) = map.get_mut(&key){
    *v = 5;
} else {
    map.insert(key, 5);

map is mutably borrowed also for the else clause, but I have lost any reference to what I borrowed, so in the else block it is false that map is borrowed as mutable more that once as the compiler complains.

Did I forget something or is this a bug?


It’s a quirk of current borrow implementation - see for more info. This issue is being worked on.

In the meantime, use the entry API on the map (it’s more ergonomic as well) to sidestep this:


It’s not my case, it was an example I built to show the bug. Thank you anyway


Ah ok. Yeah, HashMap has a nice API to work around this issue for cases like this. Similar workarounds can be used for other cases (the linked blog shows a few, and explains the general problem).