在 Rust 中将 Index 特征与 HashMap 结合使用

mik*_*ike 4 hashmap rust

为了测试这个Index特征,我编写了一个直方图。

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);
}
Run Code Online (Sandbox Code Playgroud)

测试代码在这里

但我收到以下类型错误expected &char, found char。如果我histogram[&c] += 1;改为使用,我会得到cannot borrow as mutable.

我究竟做错了什么?我该如何修复这个例子?

lje*_*drz 5

HashMap只实现Index(而不是IndexMut):

fn index(&self, index: &Q) -> &V
Run Code Online (Sandbox Code Playgroud)

所以你不能变异histogram[&c],因为返回的引用&V是不可变的。

您应该改用入口 API

for c in chars {
    let counter = histogram.entry(c).or_insert(0);
    *counter += 1;
}
Run Code Online (Sandbox Code Playgroud)

  • [Entry API](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry) 提供了一种方法。该示例解决了您的问题。 (2认同)