Iterator::map, Iterator::filter, Iterator::take, Iterator::enumerate, Iterator::chain
fn map<B, F>(self, f: F) -> Map<Self, F>
where Self: Sized, F: FnMut(Self::Item) -> B
fn filter<P>(self, predicate: P) -> Filter<Self, P>
where Self: Sized, P: FnMut(&Self::Item) -> bool
fn take(self, n: usize) -> Take<Self>
where Self: Sized
fn enumerate(self) -> Enumerate<Self>
where Self: Sized
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
where Self: Sized, U: IntoIterator<Item = Self::Item>Build a new iterator that will transform, keep, limit, number, or concatenate items. The work happens only when a consumer pulls items.
| Parameter | Description |
|---|---|
f / predicate | map takes a FnMut from Item to a new type. filter takes a FnMut that looks at each item by shared reference and returns whether to keep it. |
n | take yields at most n items and then ends. |
other | chain appends any IntoIterator whose item type matches Self::Item. |
Returns: A new iterator type such as Map or Filter. These types implement Iterator; they do not hold the finished collection until you collect or otherwise consume them.
- The first iterator is dropped before any next call, so the map closure never runs and the counter stays 0.
- filter and take are still lazy when stacked. (0..10).filter(...).take(3) only pulls enough items to fill three even numbers.
fn main() {
let mut calls = 0;
let iter = [1, 2, 3].into_iter().map(|x| {
calls += 1;
x + 1
});
drop(iter);
println!("dropped-without-collect {calls}");
calls = 0;
let v: Vec<_> = [1, 2, 3]
.into_iter()
.map(|x| {
calls += 1;
x + 1
})
.collect();
println!("after-collect {calls} {v:?}");
let evens: Vec<_> = (0..10).filter(|x| x % 2 == 0).take(3).collect();
println!("filter-take {evens:?}");
let numbered: Vec<_> = ["a", "b"].into_iter().enumerate().collect();
println!("enumerate {numbered:?}");
let chained: Vec<_> = [1, 2].into_iter().chain([3, 4]).collect();
println!("chain {chained:?}");
}Expected output
dropped-without-collect 0
after-collect 3 [2, 3, 4]
filter-take [0, 2, 4]
enumerate [(0, "a"), (1, "b")]
chain [1, 2, 3, 4]