Rust

HashMap with the entry() API

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The `entry()` API is the idiomatic way to "insert if absent" or "update if present" in a single lookup. Avoids double-lookups that the explicit `contains_key` + `insert` dance would need.
Rust
Raw
use std::collections::HashMap;

fn main() {
    let words = "the quick brown fox jumps over the lazy dog the end";
    let mut counts: HashMap<&str, u32> = HashMap::new();

    for word in words.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;       // one-line word count
    }
    println!("{:?}", counts.get("the"));             // Some(3)

    // or_insert_with — only call the closure if the key is absent
    let mut cache: HashMap<String, Vec<u8>> = HashMap::new();
    let key = "users.json".to_string();
    let bytes = cache.entry(key).or_insert_with(|| {
        std::fs::read("users.json").unwrap_or_default()
    });
    println!("cached {} bytes", bytes.len());

    // and_modify + or_insert — branch on present/absent in one call
    counts.entry("the").and_modify(|c| *c *= 10).or_insert(1);
    println!("{:?}", counts.get("the"));             // Some(30)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.