use std::collections::HashMap;
fn lookup<'a>(map: &'a mut HashMap<String, String>, key: &str) -> &'a mut String {
if let Some(s) = map.get_mut(key) {
return s;
}
let value = generate(map);
map.insert(key.into(), value);
map.get_mut(key).unwrap()
}
fn generate(_map: &mut HashMap<String, String>) -> String {
// expensive operation
todo!()
}
The above code produces the following error:
error[E0499]: cannot borrow `*map` as mutable more than once at a time
--> src/lib.rs:8:26
|
4 | fn lookup<'a>(map: &'a mut HashMap<String, String>, key: &str) -> &'a mut String {
| -- lifetime `'a` defined here
5 | if let Some(s) = map.get_mut(key) {
| --- first mutable borrow occurs here
6 | return s;
| - returning this value requires that `*map` is borrowed for `'a`
7 | }
8 | let value = generate(map);
| ^^^ second mutable borrow occurs here
s
is not live during the call to generate
. Is there a way to make this work without more than one map lookup in the common case when key
is present in the map?