// Created on savesnippets.com · https://savesnippets.com/NPtbwUTdUYEcD8 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> = 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) }