In order to test the Index
trait, I coded a histogram.
use std::collections::HashMap;
fn main() {
let mut histogram: HashMap<char, u32> = HashMap::new();
let chars: Vec<_> = "Lorem ipsum dolor sit amet"
.to_lowercase()
.chars()
.collect();
for c in chars {
histogram[c] += 1;
}
println!("{:?}", histogram);
}
Test code here.
But I get following type error expected &char, found char
. If I use histogram[&c] += 1;
instead, I get cannot borrow as mutable
.
What am I doing wrong? How can I fix this example?
HashMap
only implements Index
(and not IndexMut
):
fn index(&self, index: &Q) -> &V
so you can't mutate histogram[&c]
, because the returned reference &V
is immutable.
You should use the entry API instead:
for c in chars {
let counter = histogram.entry(c).or_insert(0);
*counter += 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With