本文介绍了如何更新可变 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}
}

但这会引发错误:

Rust 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 中的元素时,我得到了预期的结果:

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?

推荐答案

不可变索引和可变索引由两个不同的特性提供:IndexIndexMut,分别.

Indexing immutably and indexing mutably are provided by two different traits: Index and IndexMut, respectively.

目前,HashMap没有实现 IndexMut,而 Vec 确实.

Currently, HashMap does not implement IndexMut, while Vec does.

删除HashMapIndexMut的提交 实现 状态:

The commit that removed HashMap's IndexMut implementation states:

此提交删除了 HashMap 和 BTreeMap 上的 IndexMut 实现,在为了防止 API 最终包含在未来索引集特征.

据我所知,假设的 IndexSet trait 将允许您为 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 中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:39