rust 29 lines · 6 steps

Aggregating Rust data with fold and entry

Three flavors of HashMap aggregation built from the same fold-and-entry pattern over a slice of orders.

Explained by highlit
1use std::collections::HashMap;
2 
3#[derive(Debug, Clone)]
4struct Order {
5 customer_id: u64,
6 region: String,
7 total: f64,
8}
9 
10fn group_orders_by_region(orders: Vec<Order>) -> HashMap<String, Vec<Order>> {
11 orders.into_iter().fold(HashMap::new(), |mut acc, order| {
12 acc.entry(order.region.clone()).or_default().push(order);
13 acc
14 })
15}
16 
17fn revenue_by_customer(orders: &[Order]) -> HashMap<u64, f64> {
18 orders.iter().fold(HashMap::new(), |mut acc, order| {
19 *acc.entry(order.customer_id).or_insert(0.0) += order.total;
20 acc
21 })
22}
23 
24fn order_counts_by_region(orders: &[Order]) -> HashMap<&str, usize> {
25 orders.iter().fold(HashMap::new(), |mut acc, order| {
26 *acc.entry(order.region.as_str()).or_insert(0) += 1;
27 acc
28 })
29}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The entry API combined with or_default or or_insert handles the missing-key case in a single expression.
  2. 2Taking owned values via into_iter lets you move data into the accumulator, while iter borrows for read-only summaries.
  3. 3fold threads a mutable accumulator through an iterator, returning it as the function's result.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Aggregating Rust data with fold and entry — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code