为了测试这个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.
我究竟做错了什么?我该如何修复这个例子?
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)