Compiler/Borrow Checker bug?


#1

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?


#2

It’s a quirk of current borrow implementation - see http://smallcultfollowing.com/babysteps/blog/2016/04/27/non-lexical-lifetimes-introduction/ 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: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry


#3

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


#4

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).