Your Rust HashMap Doesn’t Need That if/else
I want to count how many times each URL appears in a request log. That sounds like a small job. Then I start writing it:
<button data-code="use std::collections::HashMap;
fn main() {
let requests = ["/login", "/products", "/login", "/login"];
let mut counts: HashMap = HashMap::new();
for path in requests {
if counts.contains_key(path) {
let count = counts.get_mut(path).unwrap();
*count += 1;
} else {
counts.insert(path, 1);
}
}
assert_eq!(counts["/login"], 3);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::collections::HashMap;
fn main() {
let requests = ["/login", "/products", "/login", "/login"];
let mut counts: HashMap<&str, usize> = HashMap::new();
for path in requests {
if counts.contains_key(path) {
let count = counts.get_mut(path).unwrap();
*count += 1;
} else {
counts.insert(path, 1);
}
}
assert_eq!(counts["/login"], 3);
}
use std::collections::HashMap;
fn main() {
let requests = ["/login", "/products", "/login", "/login"];
let mut counts: HashMap<&str, usize> = HashMap::new();
for path in requests {
if counts.contains_key(path) {
let count = counts.get_mut(path).unwrap();
*count += 1;
} else {
counts.insert(path, 1);
}
}
assert_eq!(counts["/login"], 3);
}
There’s nothing mysterious here. Check whether the URL exists. If it does, increase its count. Otherwise, insert it with a count of one.
Still, I’ve asked the map whether it has something, waited for a yes, and then asked it to find that same thing again. Apparently we’re making small talk.
The body of that loop can be:
*counts.entry(path).or_insert(0) += 1;
*counts.entry(path).or_insert(0) += 1;
Same counts. No separate existence check, no unwrap(), and no branch for me to maintain.
That handles the counter. But before I use the same approach everywhere, there are two details worth checking: when Rust builds the default value, and whether I’m allocating a new key just to look up one I already have.
First, it helps to understand what that expression gives back.
The part after or_insert() matters
Let me split the line before the punctuation starts looking like a password:
let count = counts.entry(path).or_insert(0);
*count += 1;
let count = counts.entry(path).or_insert(0);
*count += 1;
entry(path) represents the map’s entry for that key. It can be occupied or vacant.
or_insert(0) fills a vacant entry with zero and leaves an occupied one alone. Either way, it returns a mutable reference to the stored value. Here, that’s &mut usize.
So the second line changes the number inside the map. I don’t need to insert the updated number afterwards.
For the first /login, zero goes in and becomes one. For the next /login, the existing one becomes two. The increment happens in both cases, which is why zero is the right starting value.
This version has a small but very ordinary bug:
*counts.entry(path).or_insert(1) += 1;
*counts.entry(path).or_insert(1) += 1;
The first request counts as two. I have successfully shortened the code and inflated the traffic figures.
There is also a perfectly reasonable middle ground between my original version and entry():
if let Some(count) = counts.get_mut(path) {
*count += 1;
} else {
counts.insert(path, 1);
}
if let Some(count) = counts.get_mut(path) {
*count += 1;
} else {
counts.insert(path, 1);
}
That already removes the separate existence check and the unwrap(). I’d happily read it. For this particular operation, though, entry() says everything I need in one line.
A missing group is just an empty vector
Counters are useful, but grouping is where this becomes especially convenient.
Suppose I have errors from several services and want a list of messages for each service:
<button data-code="use std::collections::HashMap;
fn main() {
let errors = [
("payments", "timeout"),
("search", "connection refused"),
("payments", "invalid currency"),
];
let mut grouped: HashMap<&str, Vec> = HashMap::new();
for (service, message) in errors {
grouped.entry(service).or_default().push(message);
}
assert_eq!(
grouped["payments"],
vec!["timeout", "invalid currency"]
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::collections::HashMap;
fn main() {
let errors = [
("payments", "timeout"),
("search", "connection refused"),
("payments", "invalid currency"),
];
let mut grouped: HashMap<&str, Vec<&str>> = HashMap::new();
for (service, message) in errors {
grouped.entry(service).or_default().push(message);
}
assert_eq!(
grouped["payments"],
vec!["timeout", "invalid currency"]
);
}
use std::collections::HashMap;
fn main() {
let errors = [
("payments", "timeout"),
("search", "connection refused"),
("payments", "invalid currency"),
];
let mut grouped: HashMap<&str, Vec<&str>> = HashMap::new();
for (service, message) in errors {
grouped.entry(service).or_default().push(message);
}
assert_eq!(
grouped["payments"],
vec!["timeout", "invalid currency"]
);
}
or_default() uses the value type’s Default implementation when the entry is missing. For a vector, that gives me an empty vector. Then push() adds the message through the returned mutable reference.
The map’s type annotation earns its place here. It tells Rust that each group is a Vec<&str>, and it tells me what I’m building before I read the loop.
I can use this for orders grouped by customer, files grouped by extension, or validation messages grouped by field. The surrounding application changes. The bookkeeping barely does.
These examples borrow string slices from fixed input. If the result needs to own its text, I’d choose owned types such as String instead. entry() doesn’t change those lifetime requirements.
Sometimes the first value deserves different treatment
To keep the slowest response time for each route, I can start with its first measurement and update it when a slower one arrives:
<button data-code="use std::collections::HashMap;
fn main() {
let samples = [
("/login", 42_u64),
("/products", 90),
("/login", 65),
("/login", 38),
];
let mut slowest: HashMap = HashMap::new();
for (path, milliseconds) in samples {
slowest
.entry(path)
.and_modify(|current| {
*current = (*current).max(milliseconds);
})
.or_insert(milliseconds);
}
assert_eq!(slowest["/login"], 65);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::collections::HashMap;
fn main() {
let samples = [
("/login", 42_u64),
("/products", 90),
("/login", 65),
("/login", 38),
];
let mut slowest: HashMap<&str, u64> = HashMap::new();
for (path, milliseconds) in samples {
slowest
.entry(path)
.and_modify(|current| {
*current = (*current).max(milliseconds);
})
.or_insert(milliseconds);
}
assert_eq!(slowest["/login"], 65);
}
use std::collections::HashMap;
fn main() {
let samples = [
("/login", 42_u64),
("/products", 90),
("/login", 65),
("/login", 38),
];
let mut slowest: HashMap<&str, u64> = HashMap::new();
for (path, milliseconds) in samples {
slowest
.entry(path)
.and_modify(|current| {
*current = (*current).max(milliseconds);
})
.or_insert(milliseconds);
}
assert_eq!(slowest["/login"], 65);
}
and_modify() runs its closure only for an occupied entry. A missing route skips that closure and gets its first measurement through or_insert().
For the earlier counter, I’d keep the simpler increment. Here, the chain makes the two cases explicit.
“Insert only if missing” doesn’t mean “build only if missing”
There’s a detail here that’s easy to overlook when the default is just a number.
Consider this complete example:
String {
println!("Building the default message");
String::from("Please try again later")
}
fn main() {
let mut messages = HashMap::new();
messages.insert("timeout", String::from("Request timed out"));
messages.entry("timeout").or_insert(build_message());
assert_eq!(messages["timeout"], "Request timed out");
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::collections::HashMap;
fn build_message() -> String {
println!("Building the default message");
String::from("Please try again later")
}
fn main() {
let mut messages = HashMap::new();
messages.insert("timeout", String::from("Request timed out"));
messages.entry("timeout").or_insert(build_message());
assert_eq!(messages["timeout"], "Request timed out");
}
use std::collections::HashMap;
fn build_message() -> String {
println!("Building the default message");
String::from("Please try again later")
}
fn main() {
let mut messages = HashMap::new();
messages.insert("timeout", String::from("Request timed out"));
messages.entry("timeout").or_insert(build_message());
assert_eq!(messages["timeout"], "Request timed out");
}
The existing message stays. But the println! still runs.
Rust evaluates the argument build_message() before calling or_insert(). The method receives the finished string, discovers it isn’t needed, and drops it.
To defer the work, I pass the function itself:
messages.entry("timeout").or_insert_with(build_message);
messages.entry("timeout").or_insert_with(build_message);
Now the function is called only for a missing entry. If building the value needs local variables, I can pass a closure instead.
With zero, eager evaluation is uninteresting. With a function that allocates, logs, or does expensive work, it becomes a very different conversation. A method name containing “or” doesn’t give its arguments the short-circuit behaviour of ||.
I still check what creating the key costs
There’s one reason I wouldn’t mechanically replace every update branch with entry().
For a HashMap<String, usize>, this is convenient when the incoming path is a borrowed &str:
*counts.entry(path.to_owned()).or_insert(0) += 1;
*counts.entry(path.to_owned()).or_insert(0) += 1;
But entry() takes an owned key. That conversion happens even when the map already contains the path. Making the default value lazy doesn’t make the key conversion lazy too.
If most requests repeat existing paths, I can avoid creating a new String on those hits:
if let Some(count) = counts.get_mut(path) {
*count += 1;
} else {
counts.insert(path.to_owned(), 1);
}
if let Some(count) = counts.get_mut(path) {
*count += 1;
} else {
counts.insert(path.to_owned(), 1);
}
get_mut() can look up a String key using a borrowed &str. This version only allocates the owned key when it needs to insert one, at the cost of a separate insertion operation on misses. Which trade-off matters depends on the workload.
If I already own a String I can move into the map, that particular reason for keeping the branch goes away.
For the original request counter, I’m happy with:
*counts.entry(path).or_insert(0) += 1;
*counts.entry(path).or_insert(0) += 1;
And for the grouped errors:
grouped.entry(service).or_default().push(message);
grouped.entry(service).or_default().push(message);
Both leave me reading the operation I care about. Count this request. Add this error to its group. I can spend the next few lines dealing with why the payments service keeps timing out.
For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample


