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

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.