I'm trying to build up a hashmap that counts character frequencies in a string. My approach is to fold over the characters in the string, incrementing the count for the current character at each iteration. Unfortunately, rust is telling me that I'm doing something wrong with borrows.
No variation of using clone()
or breaking out the hm.get(&c)
onto a separate line has any effect.
I don't see how to avoid this error about two-phase borrows. (relevant rust-lang github issue)
use std::collections::HashMap;
fn main() {
let some_str = "some string";
let hm = some_str.chars().fold(HashMap::new(), |mut hm, c| {
match hm.get(&c) {
None => hm.insert(c, 1),
Some(i) => hm.insert(c, i + 1),
};
hm
});
for (key, val) in hm.iter() {
println!("{}: {}", key, val);
}
}
which gives this error
warning: cannot borrow `hm` as mutable because it is also borrowed as immutable
--> dank.rs:9:24
|
7 | match hm.get(&c) {
| -- immutable borrow occurs here
8 | None => hm.insert(c, 1),
9 | Some(i) => hm.insert(c, i+1)
| ^^ - immutable borrow later used here
| |
| mutable borrow occurs here
|
= note: `#[warn(mutable_borrow_reservation_conflict)]` on by default
= warning: this borrowing pattern was not meant to be accepted, and may become a hard error in the future
= note: for more information, see issue #59159 <https://github.com/rust-lang/rust/issues/59159>