Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Iterator adapter
- A step such as the shown map or filter that wraps an iterator and applies its callback when items are requested.
- Consumer
- An operation that requests items. Some request the whole stream and some stop early; a method taking self by value moves a non-Copy iterator value unless the receiver is a borrow.
- into_iter
- For Vec<T> by value, IntoIterator consumes the vector and yields owned T values. Reference receivers can instead yield borrowed items.
- retain
- Keeps only the elements for which a test returns true, changing the Vec in place.
- Short-circuiting
- Stopping a pipeline early, as collect into Result does at the first Err.
Adapters describe how to request items
A Rust iterator produces items through next. Adapters such as map and filter build another iterator that transforms or selects items when requested. A consumer such as collect, sum or a loop requests items; some consumers stop before the source is exhausted.
The item type also carries the access contract. iter borrows elements, iter_mut borrows them mutably, and into_iter uses the collection’s IntoIterator implementation. For a Vec, owned iteration consumes the vector, while borrowed iteration leaves ownership with the caller. Choose both the item access and the consumer to fit the task.
01Laziness
The Map callback waits for an item request
A candle shop imports delivery lots, clears sold-out scents and reconciles an order file. The tools must retain each delivery, keep the remaining shelf in order, and report every rejected physical row. Trace when a pipeline requests data and which collection remains available to its caller.
A reduced delivery preview doubles three lot quantities so each transformation is visible in the trace. Predict where built appears, then follow the final sum that requests those items.
fn main() {
let lots = [1, 2, 3];
let doubled = lots.iter().map(|lot| {
println!("map {lot}");
lot * 2
});
println!("built");
let total: i32 = doubled.sum();
println!("total {total}");
}
rustc --edition=2024 main.rs -o main && ./main
Use the Rust command shown with the examples. The printed trace lines instrument callback execution; distinguish constructing an adapter from requesting an item through it.
02Item by item
This map/filter chain runs item by item
Another preview converts ten-candle pack counts into quantities and keeps the larger lots. Both mapping and selection log their work. Predict whether the trace is grouped by stage or by requested item.
fn main() {
let lots = [1, 2, 3];
let kept: Vec<i32> = lots
.iter()
.map(|lot| {
println!("map {lot}");
lot * 10
})
.filter(|lot| {
println!("filter {lot}");
*lot > 10
})
.collect();
println!("{kept:?}");
}
03Which loop owns what
The receiver type decides what the loop takes
The shelf tool still needs its scent list after displaying it. Trace what the shown Vec<String> loop takes, then predict whether the later count is available.
fn main() {
let scents = vec!["fig".to_owned(), "pine".to_owned()];
for scent in scents {
println!("{scent}");
}
println!("{} scents", scents.len());
}
04Stopping early
collect into a Result stops at the first error
The importer first checks whether an entire tiny batch can be decoded. Its counter records which fields are inspected. Predict how the collected Result affects the later field after x.
fn main() {
let fields = ["1", "x", "3"];
let mut parsed = 0;
let all: Result<Vec<u32>, _> = fields
.iter()
.map(|field| {
parsed += 1;
field.parse::<u32>()
})
.collect();
println!("{} {}", all.is_err(), parsed);
}
05Repair the candle shop
Restock, clear sold-out scents, then report
The shop needs three working tools: append delivery lots, remove sold-out scents while preserving shelf order, and reconcile an order file’s accepted quantities and rejected physical row numbers.
This lab is Rust-only. Each file contains its imports, reader and complete caller.
Repair the candle shop
Retain deliveries, clear adjacent sold-out records, then reconcile all order rows without duplicating rejection evidence.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?