Iterator Pipeline for Data Transformation
Chain iterator adapters to filter, map, and fold a collection lazily, expressing a transformation pipeline without intermediate vectors.
Code
#[derive(Debug)]
struct Sale {
region: String,
amount: i64,
}
fn total_by_region(sales: &[Sale], region: &str) -> i64 {
sales
.iter()
.filter(|sale| sale.region == region)
.map(|sale| sale.amount)
.filter(|amount| *amount > 0)
.sum()
}
fn main() {
let sales = vec![
Sale { region: "eu".into(), amount: 120 },
Sale { region: "us".into(), amount: 80 },
Sale { region: "eu".into(), amount: -10 },
];
let top: Vec<&Sale> = sales
.iter()
.filter(|sale| sale.amount > 0)
.collect();
println!("eu total = {}", total_by_region(&sales, "eu"));
println!("positive sales = {}", top.len());
}How it works
Count the functions total_by_region and main as the entire surface area of Iterator Pipeline for Data Transformation.
Using it
The primary signature is fn total_by_region(sales: &[Sale], region: &str) -> i64
The demo output is labeled (eu total =, positive sales =), so every printed line maps back to its originating operation.
The demo flow inside main is total_by_region — run the file to see it end to end.
Key statements
fn total_by_region(sales: &[Sale], region: &str) -> i64 {
sales
.iter()
.filter(|sale| sale.region == region)
.map(|sale| sale.amount)
.filter(|amount| *amount > 0)
.sum()
}
.filter(|sale| sale.amount > 0)
.collect();
Interactive Tools for This Topic
FAQ
- What does Iterator Pipeline for Data Transformation print when run?
- Execute the whole file; each printed line is prefixed with a label like `eu total =`, `positive sales =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.