How to Update a Value in a Mutable HashMap in Rust

Created
Modified

Using get_mut Method

The get_mut() method returns a mutable reference to the value corresponding to the key. See the following example:

use std::collections::HashMap;

fn main() {
  let mut map = HashMap::new();
  map.insert("a", 1);

  // Update a
  *map.get_mut("a").unwrap() += 10;

  println!("{}", map["a"]);
}
11

Using entry Method

You can use entry() to update a value in a mutable HashMap:

use std::collections::HashMap;

fn main() {
  let mut map = HashMap::new();
  map.insert("a", 1);

  // Update a
  *map.entry("a").or_insert(0) += 10;

  println!("{}", map["a"]);
}
11

Using insert Method

You can use insert() to update a value of the key:

use std::collections::HashMap;

fn main() {
  let mut map = HashMap::new();
  map.insert("a", 1);

  // Update a
  map.insert("a", 10 + if map.contains_key("a") { map["a"] } else { 0 });

  println!("{}", map["a"]);
}
11

Rust Compile Errors

cannot assign to data in an index of `HashMap<&str, i32>`:

map["a"] += 10;
error[E0594]: cannot assign to data in an index of `HashMap<&str, i32>`
 --> src/main.rs:9:3
  |
9 |   map["a"] += 10;
  |   ^^^^^^^^^^^^^^ cannot assign
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<&str, i32>`

failed to resolve: use of undeclared type `HashMap`:

let mut map = HashMap::new();
error[E0433]: failed to resolve: use of undeclared type `HashMap`
 --> src/main.rs:4:17
  |
4 |   let mut map = HashMap::new();
  |                 ^^^^^^^ not found in this scope
  |
help: consider importing this struct
  |
3 | use std::collections::HashMap;

Related Tags