I've been pulling my hair out trying to implement this function (playground):
type MyMap = HashMap<Foo, Bar>;
fn try_get(map: &mut MyMap, key: Foo) -> Result<&mut Bar, &mut MyMap> {
match map.get_mut(&key) {
Some(v) => Ok(v),
None => Err(map)
}
}
(I know it seems silly here, but my actual function is more complex and basically boils down to this)
I'm pretty sure this should be possible, as we don't actually need the borrow introduced by the match
in the None
branch, but I can't get the borrow checker to accept it.
I tried using an if let
with early return, but this doesn't work either...
Is there a way to express this without unsafe
shenanigans?
Thanks!