Avoid Waste With entry or_insert_with And Borrow
Pair borrowed &str lookups via get_mut with entry().or_insert_with_key() on HashMap<String, V> so keys and defaults allocate only on cache misses.
Code
use std::collections::HashMap;
#[derive(Debug)]
struct Bucket {
label: String,
hits: u32,
}
fn record_hit(buckets: &mut HashMap<String, Bucket>, key: &str, builds: &mut u32) -> u32 {
if let Some(existing) = buckets.get_mut(key) {
existing.hits += 1;
existing.hits
} else {
let entry = buckets.entry(key.to_owned()).or_insert_with_key(|owned_key| {
*builds += 1;
Bucket { label: format!("bucket:{owned_key}"), hits: 0 }
});
entry.hits += 1;
entry.hits
}
}
fn main() {
let mut buckets: HashMap<String, Bucket> = HashMap::new();
let mut allocations = 0_u32;
for key in ["auth", "billing", "auth", "auth", "search", "billing"] {
let count = record_hit(&mut buckets, key, &mut allocations);
println!("key={key:<7} hits={count} builds={allocations}");
}
println!("total unique buckets={} (builds={allocations})", buckets.len());
println!("sample label: {}", buckets["auth"].label);
}Implementation trace — Avoid Waste With entry or_insert_with And Borrow
The code’s whole job belongs to the functions record_hit and main.
The cycling part of this snippet is for key in ["auth", "billing", "auth", "auth", "search", "billing"].
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Applying it
Signature: fn record_hit(buckets: &mut HashMap<String, Bucket>, key: &str, builds: &mut u32) -> u32
The file’s steps show up in the output as key=, total unique buckets=, sample label:.
main sequences record_hit; executing the file runs that flow once.
Statements that matter
if let Some(existing) = buckets.get_mut(key) {
existing.hits += 1;
existing.hits
} else {
let entry = buckets.entry(key.to_owned()).or_insert_with_key(|owned_key| {
*builds += 1;
Bucket { label: format!("bucket:{owned_key}"), hits: 0 }
});
entry.hits += 1;
entry.hits
}
Interactive Tools for This Topic
FAQ
- What does Avoid Waste With entry or_insert_with And Borrow print when run?
- No setup needed: run the file and look for labeled lines like `key=`, `total unique buckets=`, `sample label:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.