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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
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.