I'm attempting to count the character frequency in a string and store the count of each character in a BTreeMap
. However, I'm getting a warning and would like to get rid of it.
This is what I've tried:
use std::collections::BTreeMap;
fn letter_frequency(input: &str) -> BTreeMap<char, i32> {
let mut tree: BTreeMap<char, i32> = BTreeMap::new();
for item in &input.chars().collect::<Vec<char>>() {
match tree.get(item) {
Some(count) => tree.insert(*item, *count + 1),
None => tree.insert(*item, 1)
};
}
tree
}
This is the warning:
warning: cannot borrow `tree` as mutable because it is also borrowed as immutable
--> src/lib.rs:7:28
|
6 | match tree.get(item) {
| ---- immutable borrow occurs here
7 | Some(count) => tree.insert(*item, *count + 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>
How do I correctly use match
with a BTreeMap
to avoid the error ?