如何在Rust中更新可变HashMap中的值?
你好!我刚开始学习Rust,在使用`HashMap`时遇到了问题。我有一个可变的哈希表,存储着"用户名" -> "分数"的键值对。我想更新已有键的值,例如将分数增加10。
这是我的代码:
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice".to_string(), 50);
scores.insert("Bob".to_string(), 30);
// 尝试更新Alice的分数
let key = "Alice".to_string();
scores[key] += 10; // 错误!
println!("{:?}", scores);
}
```
编译器报错:`cannot index into a value of type HashMap`。我明白`HashMap`没有为可变访问实现`IndexMut` trait,但如何正确更新值呢?我试过使用`get_mut()`,但仍然对借用感到困惑。
请告诉我,在Rust中如何正确修改`HashMap`中的值?最好