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

This example demonstrates how to use hashmap entry api in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Collections Examples