Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Index trait with HashMap in Rust [duplicate]

Tags:

hashmap

rust

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?

like image 832
mike Avatar asked Sep 02 '25 10:09

mike


1 Answers

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;
}
like image 145
ljedrz Avatar answered Sep 04 '25 09:09

ljedrz