Insert a key value pair into a hashmap or edit it if it already exists

I need to insert a value into a hashmap, or alternatively if iit already exists, simply edit the value. I'd use the try_insert() method, but that's nightly-only, so i can't use it.

Use the Entry API.

    let value_ref: &mut i32 = hm
        .entry(key)
        .or_insert(0);

    *value_ref += 1;

Playground.

3 Likes