RRust By Example
intermediateCollections

HashMap Entry API

Use the entry API for conditional insert and update.

HashMap Entry API

Use the entry API for conditional insert and update.

Difficulty

Intermediate

Code

rust
use std::collections::HashMap;

fn main() {
    let mut map: HashMap<&str, i32> = HashMap::new();

    // insert if absent
    map.entry("a").or_insert(1);
    map.entry("a").or_insert(999); // won't overwrite

    // update based on existing value
    let text = "hello world hello";
    let mut word_count: HashMap<&str, i32> = HashMap::new();
    for word in text.split_whitespace() {
        let count = word_count.entry(word).or_insert(0);
        *count += 1;
    }
    println!("{:?}", word_count);
}

Explanation

Entry API for conditional insert and update.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples