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)
Syntax
fn entry(&mut self, key: K) -> Entry<'_, K, V>
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
HashMap get, insert, remove and iteration· Look up, add and remove map entries, and iterate in a deterministic order by sorting keys or using BTreeMap.- Rust Collections: Vec, HashMap and More · tutorial