0Pricing
Learn Rust Coding · Lesson

Adapters and Consumers

Chaining operations.

Two Kinds of Methods

Iterator methods fall into two groups:

  • Adapters return a new iterator and are lazy (map, filter, take)
  • Consumers run the iterator and produce a final value (sum, collect, for_each)

Every pipeline is zero or more adapters followed by exactly one consumer.

take: Limit the Count

take(n) yields at most n items, then stops. It is an adapter, so it stays lazy.

It works even on infinite iterators, taking only what you ask for.

fn main() {
    let first_three: Vec<i32> = (1..).take(3).collect();
    println!("{:?}", first_three);
}

All lessons in this course

  1. The Iterator Trait
  2. map, filter, collect
  3. Adapters and Consumers
  4. Custom Iterators
← Back to Learn Rust Coding