【发布时间】:2015-08-05 12:32:50
【问题描述】:
这是我想要做的:
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 中的元素时,我得到了预期的结果:
let mut my_vec = vec![1, 2, 3];
my_vec[0] += 10;
println! {"{:?}", my_vec};
// [11, 2, 3]
HashMap 与我收到上述错误有何不同?有没有办法更新值?
【问题讨论】: