【问题标题】:Use Index trait with HashMap in Rust [duplicate]在 Rust 中使用 Index trait 和 HashMap [重复]
【发布时间】:2017-11-03 17:55:41
【问题描述】:

为了测试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);
}

测试代码here.

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

我做错了什么?我该如何解决这个例子?

【问题讨论】:

    标签: hashmap rust


    【解决方案1】:

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

    fn index(&self, index: &Q) -> &V
    

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

    您应该改用entry API

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

    【讨论】:

    • 如果我想用括号运算符更新直方图,我该怎么办?是否可以为HashMap 实现IndexMut
    • Entry API 提供了一种方法。该示例解决了您的问题。
    • @mike 你不能为HashMap 实现IndexMut,因为只有在当前 crate 中定义的特征才能实现类型参数 (E0210)。我认为它没有在 std 中实现,有利于入口 API。
    • 它已被删除“[...] 以确保 API 不会在未来包含 IndexSet 特征。” github.com/rust-lang/rust/pull/23559 ...为什么!?像 C++ 这样简洁的地图更新太漂亮了!
    猜你喜欢
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2021-10-01
    相关资源
    最近更新 更多