std-method
HashMap::entry
Obtain a handle to an occupied or vacant position using an owned key. The entry can modify an existing value or initialize a missing one while borrowing the map mutably. Unlike get, entry takes K, not a borrowed Q. Expected stdout (not executed): 2 1 Common mistake: Allocating a new String for every lookup that only needs get.
Formal Syntax & Structure
rust syntaxrust
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>Working Example
Example Snippetrust
fn main() { use std::collections::HashMap; let mut count: HashMap<&str, u32> = HashMap::new(); for word in ["red", "blue", "red"] { *count.entry(word).or_default() += 1; } println!("{} {}", count["red"], count["blue"]);}