Iterator

Iterator adapters and consumers, including laziness, collect, and by_ref so a later consumer can take the rest.

主题页正文目前为英文。

Iterator is a standard-library trait in std::iter. The required method is next, which returns Option<Self::Item>. Most of the methods on the trait are provided adapters or consumers built from next. This page covers the adapters and consumers used most often; it is not a list of every method.

Adapter methods such as map, filter, take, enumerate, and chain take self and return a new iterator. They are lazy: creating the adapter does no work on the elements. A consumer such as collect, fold, sum, find, any, count, or a for loop drives next until it is finished. into_iter() consumes a collection; iter() borrows it and usually yields references.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Iterator::map, Iterator::filter, Iterator::take, Iterator::enumerate, Iterator::chainBuild a new iterator that will transform, keep, limit, number, or concatenate items. The work happens only when a consumer pulls items.
Iterator::collect, Iterator::fold, Iterator::sum, Iterator::find, Iterator::any, Iterator::count, Iterator::by_refDrive an iterator to a value, and use by_ref when a later consumer should see the remaining items.

Adapters are lazy

map applies a function to each item, filter keeps items for which a predicate returns true, take yields only the first n items, enumerate adds a 0-based index, and chain concatenates two iterators with the same item type. Because these methods only build an iterator, a map closure does not run if the iterator is dropped without a consumer. After collect, the same closure has run once per yielded item.

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.

ParameterDescription
f / predicatemap 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.
ntake yields at most n items and then ends.
otherchain 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.
rust
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]

Official documentation →

Consumers and by_ref

collect builds a collection that implements FromIterator, such as Vec, String, Result, or a map. The target type is often written explicitly, for example let v: Vec<_>. fold threads an accumulator through every item. sum is a specialized reduction. find and any take &mut self, so they can stop early and leave later items unconsumed when you still hold the iterator. count, sum, and collect take self and consume the iterator.

by_ref borrows the iterator so you can apply an adapter such as take without giving the iterator away. After that adapter is consumed, the original iterator can still yield the remaining items. If you call take directly on the iterator, the iterator is moved and the rest is lost.

Iterator::collect, Iterator::fold, Iterator::sum, Iterator::find, Iterator::any, Iterator::count, Iterator::by_ref

fn collect<B>(self) -> B
    where B: FromIterator<Self::Item>, Self: Sized
fn fold<B, F>(self, init: B, f: F) -> B
    where Self: Sized, F: FnMut(B, Self::Item) -> B
fn sum<S>(self) -> S
    where Self: Sized, S: Sum<Self::Item>
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
    where Self: Sized, P: FnMut(&Self::Item) -> bool
fn any<F>(&mut self, f: F) -> bool
    where Self: Sized, F: FnMut(Self::Item) -> bool
fn count(self) -> usize
    where Self: Sized
fn by_ref(&mut self) -> &mut Self
    where Self: Sized

Drive an iterator to a value, and use by_ref when a later consumer should see the remaining items.

ParameterDescription
init / ffold starts from init and then calls f with the accumulator and each item.
predicate / ffind and any take a closure. any returns as soon as the closure is true.

Returns: collect returns the built collection. fold and sum return the accumulated value. find returns Option<Item>. any returns a bool. count returns the number of items. by_ref returns a mutable reference to the same iterator.

  • count consumes the iterator after map in this example, so the doubled values are produced and then discarded except for the count.
  • The by_ref example follows the official pattern: take the first two words through a borrow, then collect the rest from the same iterator.
rust
fn main() {
    let mut words = ["hello", "world", "of", "Rust"].into_iter();
    let first: Vec<_> = words.by_ref().take(2).collect();
    let rest: Vec<_> = words.collect();
    println!("by_ref {first:?} {rest:?}");

    let sum: i32 = [1, 2, 3].into_iter().sum();
    let folded = [1, 2, 3].into_iter().fold(0, |acc, x| acc + x);
    let found = [1, 2, 3].into_iter().find(|x| *x == 2);
    let any = [1, 2, 3].into_iter().any(|x| x > 2);
    let count = [1, 2, 3].into_iter().map(|x| x * 2).count();
    println!("sum {sum} fold {folded} find {found:?} any {any} count {count}");
}

Expected output

by_ref ["hello", "world"] ["of", "Rust"]
sum 6 fold 6 find Some(2) any true count 3

Official documentation →