Use Index trait with HashMap in Rust

Viewed 3560

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?

1 Answers
Related