Open
Description
I tried this code:
use std::collections::HashMap;
fn f1(map: &mut HashMap<i32, String>, k: i32) -> &String {
if let Some(s) = map.get(&k) {
return s;
}
map.insert(k, k.to_string());
map.get(&k).unwrap()
}
async fn f2(map: &mut HashMap<i32, String>, k: i32) -> &String {
if let Some(s) = map.get(&k) {
return s;
}
map.insert(k, k.to_string());
map.get(&k).unwrap()
}
f2
seems to be correct but can not be compiled.
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:15:5
|
12 | if let Some(s) = map.get(&k) {
| --- immutable borrow occurs here
13 | return s;
| - returning this value requires that `*map` is borrowed for `'1`
14 | }
15 | map.insert(k, k.to_string());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
16 | map.get(&k).unwrap()
17 | }
| - return type of generator is &'1 std::string::String
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
Meta
According to the playground, the problem exists on 1.44.1
and 1.46.0-nightly (2020-07-04 0cd7ff7ddfb75a38dca8)
.
Other versions may be the same.