Rust 1.99 (2024 edition) reference · Vec and HashMap

Rust HashMap::entry Method

Insert or update a map value in one lookup: count occurrences, append to lists, or insert a default if missing.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn entry(&mut self, key: K) -> Entry<'_, K, V>

Parameters

ParameterDescription
or_insert(v) Insert v if missing; returns &mut V.
or_insert_with(|| ...) Lazy default.
or_default() V::default().
and_modify(|v| ...) Change an existing value.

Examples

Example 1
use std::collections::BTreeMap;

fn main() {
    let mut counts: BTreeMap<&str, u32> = BTreeMap::new();
    for word in "a b a c b a".split(' ') {
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{counts:?}");
}

Output

{"a": 3, "b": 2, "c": 1}

Run this on your computer — see “Get Started” for setup.

Grouping into lists
use std::collections::HashMap;

fn main() {
    let mut by_team: HashMap<&str, Vec<&str>> = HashMap::new();
    for (team, person) in [("api", "ana"), ("web", "ben"), ("api", "cy")] {
        by_team.entry(team).or_default().push(person);
    }
    let mut teams: Vec<_> = by_team.into_iter().collect();
    teams.sort();
    println!("{teams:?}");
}

Output

[("api", ["ana", "cy"]), ("web", ["ben"])]

Run this on your computer — see “Get Started” for setup.

Was this page helpful?