dictionaryrust

How to increment a counter in a map and get the current count


Can I do this in one expression?

*map.entry(key).or_default() += 1;
let count = *map.get(&key).unwrap();

Ideally, I would like this to be an atomic operation, but I can lock if needed.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=df6778cd1312c31eb230a545c6c2b6ce


Solution

  • You can:

    let count = *map.entry(key).and_modify(|v| *v += 1).or_insert(1);
    

    This will: