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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The entry API combined with or_default or or_insert handles the missing-key case in a single expression.
- 2Taking owned values via into_iter lets you move data into the accumulator, while iter borrows for read-only summaries.
- 3fold threads a mutable accumulator through an iterator, returning it as the function's result.
Related explainers
rust
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
rust
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::Duration;
Building a thread pool in Rust
concurrency
channels
thread-pool
Advanced
9 steps
rust
use std::time::Instant; use tracing::info; pub struct Timer {
A scope-guard timer with Drop in Rust
raii
drop-guard
timing
Intermediate
7 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use uuid::Uuid;
Building a typed create_user handler in Axum
serde
extractors
sqlx
Intermediate
7 steps
rust
use axum::{ response::sse::{Event, KeepAlive, Sse}, routing::get, Router,
Streaming live price ticks with SSE in Axum
server-sent-events
broadcast-channel
streaming
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/aggregating-rust-data-with-fold-and-entry-explained-rust-aa63/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.