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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
php
<?php namespace App\Services\Reports;
Streaming a monthly revenue CSV in Laravel
csv-export
lazy-collections
eloquent-query
Intermediate
8 steps
rust
use std::sync::mpsc; use std::thread; use std::time::Duration;
Running work with a timeout in Rust
concurrency
channels
timeout
Intermediate
7 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.