这是我想要做的:
use std::collections::HashMap;
fn main() {
let mut my_map = HashMap::new();
my_map.insert("a", 1);
my_map.insert("b", 3);
my_map["a"] += 10;
// I expect my_map becomes {"b": 3, "a": 11}
}
但这会引发错误:
锈2015年
error[E0594]: cannot assign to immutable indexed content
--> src/main.rs:8:5
|
8 | my_map["a"] += 10;
| ^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<&str, i32>`
Rust 2018
error[E0594]: cannot assign to data in a `&` reference
--> src/main.rs:8:5
|
8 | my_map["a"] += 10;
| ^^^^^^^^^^^^^^^^^ cannot assign
我真的不明白这意味着什么,因为我让HashMap
变得可变。当我尝试更新vector
中的元素时,我得到了预期的结果:
let mut my_vec = vec![1, 2, 3];
my_vec[0] += 10;
println! {"{:?}", my_vec};
// [11, 2, 3]
有什么不同的HashMap
,我得到上述错误?有没有办法更新价值?
可变地索引和可变索引由两个不同的特征提供:Index
和IndexMut
。
目前,HashMap
没有实施IndexMut
,而Vec
does。
The commit that removed HashMap
's IndexMut
implementation说:
此提交将删除HashMap和BTreeMap上的IndexMut impls,以便针对最终包含的IndexSet特征进行面向未来的证明。
我的理解是,假设的IndexSet
特性允许您为HashMap
分配全新的值,而不仅仅是读取或改变现有条目:
let mut map = HashMap::new();
map["key"] = "value";
现在,您可以使用get_mut
:
*my_map.get_mut("a").unwrap() += 10;
或者entry
API:
*my_map.entry("a").or_insert(42) += 10;