更新可变HashMap中的值 [英] Update value in mutable HashMap
问题描述
使用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;
//我的预期输出是my_map变成{b:3,a:11}
}
引发以下错误:
$ b
error:can not assign to不可变索引内容
- > src / main.rs:8:5
|
8 | my_map [a] + = 10;
| ^^^^^^^^^^^^^^^^^不能借用为可变
我真的不明白这是什么意思,因为我让 HashMap
可变。当我尝试更新向量
中的元素时,我得到了预期的结果:
let mut my_vec = vec!{1,2,3};
my_vec [0] + = 10;
println!{{:?},my_vec};
// [11,2,3]
c> HashMap ,我得到上述错误?有没有办法更新值?
不变索引和可变索引由两种不同的特征提供: Index
和 IndexMut
,分别。
目前, HashMap
不会实现 IndexMut
,而 Vec
does 。
这个提交将
顺序中的IndexMut impls移除到HashMap和BTreeMap上,以便将来-pr对于最终包含
IndexSet特征的API而言。
据我的理解,一个假设的 IndexSet
trait将允许您为全新的值赋予 HashMap
,而不仅仅是读取或改变现有的条目:
let mut map = HashMap :: new();
map [key] =value;
现在,您可以使用 get_mut
:
* my_map.get_mut(a)。unwrap()+ = 10;
或 条目
API:
* my_map.entry(a)。or_insert(42)+ = 10;
Here is what I am trying to do:
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;
// my expected outputs is my_map becomes {"b": 3, "a": 11}
}
Raises the following error:
error: cannot assign to immutable indexed content
--> src/main.rs:8:5
|
8 | my_map["a"] += 10;
| ^^^^^^^^^^^^^^^^^ cannot borrow as mutable
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]
What is different about HashMap
that I am getting the above error? Is there a way to update a value?
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:
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.
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";
For now, you can use get_mut
:
*my_map.get_mut("a").unwrap() += 10;
Or the entry
API:
*my_map.entry("a").or_insert(42) += 10;
这篇关于更新可变HashMap中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!