2017-06-02 91 views
2

为了测试Index特征,我编码了一个直方图。在Rust中使用具有HashMap的索引特征

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 &char, found char。如果我用histogram[&c] += 1;代替,我得到cannot borrow as mutable

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

回答

4

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

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

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

您应该使用entry API代替:

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

所以我能做些什么,如果我想我的更新与支架操作直方图?是否可以为'HashMap'实现'IndexMut'? – mike

+2

[Entry API](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry)提供了一种方法。这个例子解决了你的问题。 – red75prime

+0

@mike您无法为'HashMap'实现'IndexMut',因为只有当前箱子中定义的特征可以为类型参数实现([E0210](https://doc.rust-lang.org/error-的index.html#E0210))。我认为它没有在std中实现,而是赞成入门API。 – ljedrz

相关问题