如何在可变的HashMap中更新值? [英] How can I update a value in a mutable HashMap?
问题描述
这就是我想要做的:
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>`
2018年锈蚀
error[E0594]: cannot assign to data in a `&` reference
--> src/main.rs:8:5
|
8 | my_map["a"] += 10;
| ^^^^^^^^^^^^^^^^^ cannot assign
我真的不明白这意味着什么,因为我使HashMap
可变了.当我尝试更新vector
中的元素时,得到了预期的结果:
I don't really understand what that means, since I made the HashMap
mutable. When I try to update an element in a vector
, I get the expected result:
let mut my_vec = vec![1, 2, 3];
my_vec[0] += 10;
println! {"{:?}", my_vec};
// [11, 2, 3]
我收到上述错误与HashMap
有什么不同?有没有更新值的方法?
What is different about HashMap
that I am getting the above error? Is there a way to update a value?
推荐答案
不变的索引和可变的索引由两个不同的特征提供: IndexMut
.
Indexing immutably and indexing mutably are provided by two different traits: Index
and IndexMut
, respectively.
Currently, HashMap
does not implement IndexMut
, while Vec
does.
The commit that removed HashMap
's IndexMut
implementation states:
此提交将删除HashMap和BTreeMap上的IndexMut隐式, 为了将来对API进行过时验证,以防最终包含 IndexSet特征.
This commit removes the IndexMut impls on HashMap and BTreeMap, in order to future-proof the API against the eventual inclusion of an IndexSet trait.
我的理解是,假设的IndexSet
特征将使您可以为HashMap
分配全新的值,而不仅仅是读取或变异现有条目:
It's my understanding that a hypothetical IndexSet
trait would allow you to assign brand-new values to a HashMap
, and not just read or mutate existing entries:
let mut map = HashMap::new();
map["key"] = "value";
目前,您可以使用 get_mut
:
For now, you can use get_mut
:
*my_map.get_mut("a").unwrap() += 10;
或 entry
API :
Or the entry
API:
*my_map.entry("a").or_insert(42) += 10;
这篇关于如何在可变的HashMap中更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!