Blog

Part 17 · Iterators in Rust: Lazy Pipelines and collect

An iterator hands out items one at a time through next. This part shows how iter, iter_mut and into_iter differ, why map and filter do nothing until something consumes them, and how collect builds a Vec, a String or a map.

An iterator is a thing that hands you items one at a time. Every for loop you’ve written in this series used one. In Rust, iterators also chain: you can filter a list, change each item and gather the results in one line, without writing the loop yourself.

This part covers the Iterator trait and its next method, the three ways to iterate over a collection, why adapters like map and filter are lazy, the consumers that finish a pipeline, and how to write an iterator of your own. It uses closures from Part 16 everywhere, and traits from Part 14. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

This program builds a pipeline over four numbers. filter keeps the even ones, and map multiplies each one by 10. Both closures print a line when they run. Guess the order of the lines before you read on:

fn main() {
    let numbers = [1, 2, 3, 4];
    let pipeline = numbers
        .iter()
        .filter(|n| {
            println!("filter looks at {n}");
            *n % 2 == 0
        })
        .map(|n| {
            println!("map gets {n}");
            n * 10
        });
    println!("pipeline built");
    let out: Vec<i32> = pipeline.collect();
    println!("{out:?}");
}

It prints:

pipeline built
filter looks at 1
filter looks at 2
map gets 2
filter looks at 3
filter looks at 4
map gets 4
[20, 40]

Two things surprise most people. First, pipeline built comes before anything else. Building the pipeline didn’t run either closure. Second, the lines don’t come in two blocks, all the filter lines and then all the map lines. The number 2 goes through filter and then through map before 3 is even looked at.

Both come from the same design. A Rust iterator does no work until something asks it for an item, and then it does only enough work to produce that one item. The rest of this part explains how.

The Iterator trait

Iterator is a trait from the standard library. Stripped down, it looks like this:

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

type Item names the type of the items it hands out. It’s an associated type: each type that implements the trait picks one. Part 22 covers associated types; for now, read Self::Item as “the item type”.

next is the only method you have to write. Each call returns Some(item) while there are items left, and None once they’ve run out. It takes &mut self because handing out an item changes the iterator: it has to remember where it got to.

We can call next by hand:

fn main() {
    let letters = ['a', 'b', 'c'];
    let mut it = letters.iter();
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
}

It prints:

Some('a')
Some('b')
Some('c')
None
None

it has to be mut, because next changes it. After the last item, next keeps returning None. Most iterators keep returning None from then on, but the trait’s docs allow one to start again, so code shouldn’t count on either.

Every other method on an iterator, and there are dozens, is built on next. They come as default methods of the trait, the way Part 14 showed. Write next, and you get map, filter, sum and the rest for free.

A for loop is next in a loop

A for loop is a short way to write a while let loop around next. These two loops do the same thing:

#[allow(clippy::while_let_on_iterator)]
fn main() {
    let names = ["Ana", "Ben"];

    for name in names.iter() {
        println!("for: {name}");
    }

    let mut it = names.iter();
    while let Some(name) = it.next() {
        println!("while let: {name}");
    }
}

It prints:

for: Ana
for: Ben
while let: Ana
while let: Ben

The for version is the one to write. Clippy, Rust’s linter, flags the while let loop and suggests the for loop instead; the #[allow(...)] line above main tells it we’re doing this on purpose. The while let version is what the for loop means. There’s one more step that for takes: it first calls into_iter() on whatever you give it. That’s how for name in names works on a Vec, which isn’t an iterator itself.

iter, iter_mut and into_iter

A Vec gives you three iterators. They differ in what each item is:

Method Each item is The vector afterwards for shorthand
v.iter() &T, a shared borrow unchanged, still usable for x in &v
v.iter_mut() &mut T, a mutable borrow changed in place, still usable for x in &mut v
v.into_iter() T, the value itself moved, gone for x in v

The type annotations in this program prove each row:

fn main() {
    let mut scores = vec![10, 20, 30];

    let mut total = 0;
    for s in scores.iter() {
        let r: &i32 = s;
        total += r;
    }
    println!("total {total}");

    for s in scores.iter_mut() {
        let r: &mut i32 = s;
        *r += 1;
    }
    println!("{scores:?}");

    let names = vec![String::from("Ana"), String::from("Ben")];
    let mut owned: Vec<String> = Vec::new();
    for name in names.into_iter() {
        let n: String = name;
        owned.push(n);
    }
    println!("{owned:?}");
}

It prints:

total 60
[11, 21, 31]
["Ana", "Ben"]
  • iter() lends each item out. This is the one you’ll use most.
  • iter_mut() lends each item out mutably, so you can change it through *r. That’s the * from Part 7.
  • into_iter() moves each item out. The Strings end up owned by owned, and names is gone, the same as the for loop in Part 6.

The borrowing rules from Part 7 apply as usual. While an iter() is alive, the vector is borrowed shared, so you can’t push to it. Part 8 showed why.

into_iter() on a reference gives references: (&v).into_iter() is the same as v.iter(). That’s why for x in &v works. It also means into_iter() doesn’t always move. What it yields depends on what you call it on.

Adapters are lazy

An adapter is a method that takes an iterator and returns a new iterator: map, filter, take and many more. A consumer is a method that pulls items out until it’s done and returns a result: collect, sum, count and so on. A for loop is a consumer too.

An adapter on its own does nothing. It only wraps the iterator before it, ready to work when asked. The compiler knows this. If you write an adapter and throw the result away, like this line:

v.iter().map(|x| x * 2);

cargo build warns you:

warning: unused `Map` that must be used
 --> src/main.rs:3:5
  |
3 |     v.iter().map(|x| x * 2);
  |     ^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: iterators are lazy and do nothing unless consumed

Map is the type that map returns. It holds the old iterator and the closure, and nothing else happens until something calls its next.

When something does, the call travels backwards through the pipeline. collect calls next on map. map calls next on filter. filter calls next on the source, and keeps calling until it gets an item that passes, or None. Then the item travels forwards: filter returns it, map changes it, collect stores it. Then collect asks again. This is called a pull model: the consumer at the end pulls items through, one at a time.

The animation runs the pipeline from “Try this first” on five numbers, [1, 2, 3, 4, 5]:

source 1 2 3 4 5 filter(even) map(x*10) collect output 1 dropped 2 20 4 40 3 dropped 5 dropped [] [20] [20, 40] each stage gets one item at a time by calling next() on the stage to its left output: [] output: [] (filter asks again) output: [20] (3, 4 and 5 not read yet) output: [20, 40] (5 not read yet) output: [20, 40] done collect calls next(): nothing has been read from the source yet filter pulls 1 from the source: 1 is odd, so filter drops it filter pulls 2: it passes, map makes 20, collect pushes it 3 is pulled and dropped; 4 passes and map makes 40 5 is dropped; the source returns None, so collect stops

The consumer pulls items through one at a time. 2 is already in the output before 3 is read from the source.

Here are those steps in words, in case the animation doesn’t play for you:

  1. collect calls next on map, which calls next on filter. Nothing has been read from the source yet, and the output is empty.
  2. filter pulls 1 from the source. 1 is odd, so filter drops it and asks the source again, without returning anything.
  3. filter pulls 2. It’s even, so filter returns it. map turns it into 20, and collect pushes 20. The output is [20], and 3, 4 and 5 are still unread.
  4. collect asks again. filter pulls 3 and drops it, then pulls 4, which passes. map makes 40. The output is [20, 40].
  5. collect asks again. filter pulls 5 and drops it, then asks once more. The source returns None, so filter returns None, map returns None, and collect stops.

Laziness is not only a curiosity. It means a pipeline can stop early and skip the rest of the work. take(2) stops asking after two items, so map only runs twice, even on an iterator with no end:

fn main() {
    let first_two: Vec<u64> = (1..)
        .map(|n| {
            println!("squaring {n}");
            n * n
        })
        .take(2)
        .collect();
    println!("{first_two:?}");
}

It prints:

squaring 1
squaring 2
[1, 4]

1.. is a range with no end, and ranges are iterators. Without laziness, map would try to square every number there is. With it, the program does exactly two multiplications.

Consumers

A consumer runs the pipeline and returns one result. Here are the common ones on a small list:

fn main() {
    let temps = [18, 23, 19, 30, 25];

    let total: i32 = temps.iter().sum();
    let hot_days = temps.iter().filter(|t| **t >= 25).count();
    let product = temps.iter().fold(1_i64, |acc, t| acc * i64::from(*t));

    println!("total {total}, hot days {hot_days}, product {product}");
    println!("min {:?}, max {:?}", temps.iter().min(), temps.iter().max());
    println!("any over 28: {}", temps.iter().any(|t| *t > 28));
    println!("all over 15: {}", temps.iter().all(|t| *t > 15));
    println!("first over 20: {:?}", temps.iter().find(|t| **t > 20));
    println!("position of 30: {:?}", temps.iter().position(|t| *t == 30));

    let empty: Vec<i32> = Vec::new();
    println!("max of nothing: {:?}", empty.iter().max());
}

It prints:

total 115, hot days 2, product 5899500
min Some(18), max Some(30)
any over 28: true
all over 15: true
first over 20: Some(23)
position of 30: Some(3)
max of nothing: None
  • sum adds the items up. It needs to know the result type, which is why total has : i32.
  • count counts the items. It returns a usize.
  • fold is the general one. It starts with a value, here 1_i64, and calls the closure once per item with the value so far and the item. Whatever the closure returns becomes the new value. sum is a fold that starts at zero and adds.
  • min and max return an Option, because an empty iterator has no smallest item.
  • any and all answer yes-or-no questions. They stop as soon as they know: any at the first true, all at the first false.
  • find returns the first item that matches, and position returns its index. Both return Option and both stop at the first match.

Watch the stars. temps.iter() yields &i32. filter and find pass their closure a reference to each item, so there the closure gets &&i32, and **t gets down to the number. any, all and position pass the item itself, a &i32, so one * is enough. Comparison operators need both sides to be the same type, so the compiler will tell you when you’ve got the count wrong.

collect builds whatever you ask for

collect is the most flexible consumer. It can build almost any collection, and you choose which one by naming the type:

use std::collections::BTreeMap;
use std::collections::HashMap;

fn main() {
    let words = ["apple", "bob", "kiwi"];

    let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
    println!("{lengths:?}");

    let initials: String = words.iter().map(|w| w.chars().next().unwrap()).collect();
    println!("{initials}");

    let by_word: HashMap<&str, usize> = words.iter().map(|w| (*w, w.len())).collect();
    println!("kiwi has {} letters", by_word["kiwi"]);

    let sorted: BTreeMap<usize, &str> = words.iter().map(|w| (w.len(), *w)).collect();
    println!("{sorted:?}");
}

It prints:

[5, 3, 4]
abk
kiwi has 4 letters
{3: "bob", 4: "kiwi", 5: "apple"}
  • Items of type char collect into a String. So do &str and String items.
  • Pairs (key, value) collect into a HashMap or a BTreeMap. If two pairs have the same key, the later one wins.
  • We print a single lookup from the HashMap, not the whole map, because a HashMap‘s order changes from run to run (Part 13).

How does one method return so many types? collect is generic over its return type. Any type that implements the trait FromIterator can be the target, and Vec, String, HashMap, BTreeMap, HashSet and others all do. So collect needs to be told the target. You can tell it in two ways:

fn main() {
    let v = [1, 2, 3];

    let a: Vec<i32> = v.iter().map(|x| x * 2).collect();
    let b = v.iter().map(|x| x * 2).collect::<Vec<i32>>();
    let c = v.iter().map(|x| x * 2).collect::<Vec<_>>();

    println!("{a:?} {b:?} {c:?}");
}

It prints:

[2, 4, 6] [2, 4, 6] [2, 4, 6]

a names the type on the variable. b names it on the method with ::<>, which Rust programmers call the turbofish, after its shape. c names only the part the compiler can’t work out. The _ means “you fill this in”, and the compiler can see the items are i32. collect::<Vec<_>>() is a very common line. Use the turbofish when the result goes straight into another call and there’s no variable to annotate.

Collecting into a Result

One target is worth its own heading. An iterator of Result items can collect into a Result of a collection:

fn parse_all(inputs: &[&str]) -> Result<Vec<i32>, std::num::ParseIntError> {
    inputs.iter().map(|s| s.parse::<i32>()).collect()
}

fn main() {
    println!("{:?}", parse_all(&["4", "8", "15"]));
    println!("{:?}", parse_all(&["4", "eight", "15"]));
}

It prints:

Ok([4, 8, 15])
Err(ParseIntError { kind: InvalidDigit })

If every item is Ok, you get Ok with all the values. At the first Err, collect stops pulling and returns that error. “15” in the second call is never parsed. This works with Option too: Option<Vec<T>> is Some only if every item was Some. Together with ? from Part 12, it turns “parse every line or fail” into one expression.

Adapters you’ll use often

There are many adapters. These are the ones that turn up most:

fn main() {
    let names = ["Ana", "Ben", "Cai"];
    let ages = [31, 27, 45];

    for (i, name) in names.iter().enumerate() {
        println!("{i}: {name}");
    }

    let pairs: Vec<(&str, i32)> = names.iter().copied().zip(ages).collect();
    println!("zip: {pairs:?}");

    let all: Vec<i32> = [1, 2].iter().chain([3, 4].iter()).copied().collect();
    println!("chain: {all:?}");

    let middle: Vec<i32> = (1..=10).skip(3).take(4).collect();
    println!("skip 3, take 4: {middle:?}");

    let small: Vec<i32> = [1, 4, 9, 2, 1].into_iter().take_while(|n| *n < 5).collect();
    println!("take_while < 5: {small:?}");

    let backwards: String = "stressed".chars().rev().collect();
    println!("rev: {backwards}");

    let letters: Vec<char> = names.iter().flat_map(|n| n.chars()).collect();
    println!("flat_map: {letters:?}");
}

It prints:

0: Ana
1: Ben
2: Cai
zip: [("Ana", 31), ("Ben", 27), ("Cai", 45)]
chain: [1, 2, 3, 4]
skip 3, take 4: [4, 5, 6, 7]
take_while < 5: [1, 4]
rev: desserts
flat_map: ['A', 'n', 'a', 'B', 'e', 'n', 'C', 'a', 'i']
  • enumerate pairs each item with its index, starting at 0.
  • zip walks two iterators side by side and stops when either runs out. Its argument can be anything with into_iter, like the array ages.
  • copied turns &i32 items into i32 (and &&str into &str). It works for Copy types. For others, cloned calls clone on each one.
  • chain runs one iterator, then the next.
  • skip(n) drops the first n items, and take(n) stops after n.
  • take_while stops at the first item that fails the test. Notice the last 1 isn’t included: once it stops, it stays stopped. filter would have kept it.
  • rev walks backwards. It works on iterators that know their end, such as a slice, a range or chars.
  • flat_map maps each item to an iterator and joins them all into one.

Slices also have two methods that give you groups instead of single items. windows(n) gives every run of n neighbours, overlapping. chunks(n) cuts the slice into pieces of n, not overlapping, and the last piece may be shorter:

fn main() {
    let readings = [3, 5, 4, 8, 9, 7];

    let rises: Vec<bool> = readings.windows(2).map(|w| w[1] > w[0]).collect();
    println!("rises: {rises:?}");

    for chunk in readings.chunks(4) {
        println!("chunk {chunk:?}");
    }

    let mut it = readings.iter().peekable();
    while let Some(r) = it.next() {
        if let Some(next) = it.peek() {
            println!("{r} then {next}");
        }
    }
}

It prints:

rises: [true, false, true, true, false]
chunk [3, 5, 4, 8]
chunk [9, 7]
3 then 5
5 then 4
4 then 8
8 then 9
9 then 7

Each window and each chunk is a slice, &[i32], borrowed from readings. Nothing is copied. The last part uses peekable, which wraps an iterator so you can look at the next item with peek without taking it. Parsers use it to decide what to do based on what comes next.

Your own iterator

To make your own type an iterator, implement Iterator and write next. This Counter counts from 1 up to a limit:

struct Counter {
    count: u32,
    limit: u32,
}

impl Counter {
    fn new(limit: u32) -> Counter {
        Counter { count: 0, limit }
    }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.count < self.limit {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    for n in Counter::new(3) {
        println!("count {n}");
    }

    let total: u32 = Counter::new(10)
        .filter(|n| n.is_multiple_of(3))
        .map(|n| n * n)
        .sum();
    println!("sum of squares of multiples of 3 up to 10: {total}");

    let pairs: Vec<(u32, u32)> = Counter::new(3).zip(Counter::new(3).skip(1)).collect();
    println!("{pairs:?}");
}

It prints:

count 1
count 2
count 3
sum of squares of multiples of 3 up to 10: 126
[(1, 2), (2, 3)]

The struct holds the state: where we’ve got to, and where to stop. next moves the state on by one step and returns the item, or None at the end. That’s all. filter, map, sum, zip and skip all work on Counter straight away, because they’re default methods of the trait. The total is 9 + 36 + 81 = 126.

for n in Counter::new(3) works too. Every iterator gets an into_iter that returns itself, so a for loop accepts any iterator.

Are iterator chains slow?

A pipeline like filter(...).map(...).sum() looks like it might cost more than a plain loop: three method calls per item, and closures. In practice it usually doesn’t. Each adapter is a small struct, and each closure has its own type, so the compiler knows exactly which code runs at every step. In a release build, it inlines the calls and the result is normally the same machine code you’d get from writing the loop by hand. The Rust book calls iterators one of Rust’s zero-cost abstractions: you don’t pay for the nicer way of writing it.

An iterator over a slice can even be a little better than an index loop. for i in 0..v.len() with v[i] checks the index against the length each time, unless the optimiser can prove it’s safe. v.iter() can’t go out of bounds, so there’s nothing to check. We won’t quote timings here. If speed matters, measure your own code in a release build.

When a for loop is clearer

Iterators are good at one shape of work: items flow in, each one is changed or kept or dropped, and one result comes out. When the work has another shape, a plain for loop is often easier to read. Here’s a loop that sorts log lines into two lists and stops at the first fatal one:

fn main() {
    let lines = ["ok", "warn: disk 80%", "ok", "fatal: disk full", "ok"];
    let mut warnings = Vec::new();
    let mut ok_count = 0;

    for (i, line) in lines.iter().enumerate() {
        if line.starts_with("fatal") {
            println!("stopped at line {i}: {line}");
            break;
        } else if line.starts_with("warn") {
            warnings.push(*line);
        } else {
            ok_count += 1;
        }
    }
    println!("{ok_count} ok, warnings: {warnings:?}");
}

It prints:

stopped at line 3: fatal: disk full
2 ok, warnings: ["warn: disk 80%"]

You could write this with take_while and a fold that carries a tuple of two results. It would be shorter and harder to read. Reach for a for loop when:

  • the loop updates two or more things at once;
  • it prints or writes something as it goes, and that’s the main point;
  • it needs break, continue or return in several places;
  • it uses ? on each step, and you’d rather not collect into a Result.

A good rule is to write whichever you’d rather read in six months.

Worked example: collect into the wrong type

You have a list of names and want the ones longer than two letters, as a new Vec<String>. This is a natural first try:

fn main() {
    let names = vec![String::from("Ana"), String::from("Bo"), String::from("Cai")];
    let long: Vec<String> = names.iter().filter(|n| n.len() > 2).collect();
    println!("{long:?} {names:?}");
}

It prints:

error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&String`
    --> src/main.rs:3:66
     |
   3 |     let long: Vec<String> = names.iter().filter(|n| n.len() > 2).collect();
     |                                                                  ^^^^^^^ value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&String>`
     |
help: the trait `FromIterator<&String>` is not implemented for `Vec<String>`
      but trait `FromIterator<String>` is implemented for it
...
note: the method call chain might not have had the expected associated types
...
   3 |     let long: Vec<String> = names.iter().filter(|n| n.len() > 2).collect();
     |                                   ^^^^^^ ----------------------- `Iterator::Item` remains `&String` here
     |                                   |
     |                                   `Iterator::Item` is `&String` here

Read it in three pieces:

  • The first line says what went wrong. The target is Vec<String>. The items are &String. A vector of owned strings can’t be built out of borrowed ones, because something would have to make the owned copies, and Rust won’t do that behind your back.
  • The help says the same thing in trait terms. Remember that collect works through the trait FromIterator. Vec<String> implements FromIterator<String>, but not FromIterator<&String>.
  • The note walks along the chain and shows the item type at each step. iter() is where the items became &String, and filter kept them that way. That points at the line to change.

There are three fixes, and which one is right depends on what you want:

fn main() {
    let names = vec![String::from("Ana"), String::from("Bo"), String::from("Cai")];

    let borrowed: Vec<&String> = names.iter().filter(|n| n.len() > 2).collect();
    let cloned: Vec<String> = names.iter().filter(|n| n.len() > 2).cloned().collect();
    println!("{borrowed:?} {cloned:?}");

    let moved: Vec<String> = names.into_iter().filter(|n| n.len() > 2).collect();
    println!("{moved:?}");
}

It prints:

["Ana", "Cai"] ["Ana", "Cai"]
["Ana", "Cai"]
  1. Collect the references into a Vec<&String>. Nothing is copied, but the new vector borrows from names, so names must outlive it.
  2. Clone the ones you keep with cloned(). It calls .clone() from Part 6 on each item that reaches it, so the short name Bo is never copied. names stays usable.
  3. Move them with into_iter(). No copies are made, but names is gone after this line, and the strings that filter drops are freed.

If you leave the type off completely, the same chain fails with “type annotations needed” instead. In both cases, the fix starts with one question: do I want references, copies or the values themselves?

Worked example: a word report

This one puts several pieces together. Given some text, we want the number of words, the longest word, and how often each word appears, ignoring case and punctuation:

use std::collections::BTreeMap;

fn main() {
    let text = "The cat sat. The cat ran! A dog sat, too.";

    let words: Vec<String> = text
        .split_whitespace()
        .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()))
        .filter(|w| !w.is_empty())
        .map(|w| w.to_lowercase())
        .collect();

    println!("{} words", words.len());

    let longest = words.iter().max_by_key(|w| w.len());
    println!("a longest word: {longest:?}");

    let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
    for w in &words {
        *counts.entry(w.as_str()).or_insert(0) += 1;
    }

    let repeated: Vec<String> = counts
        .iter()
        .filter(|(_, n)| **n > 1)
        .map(|(w, n)| format!("{w} x{n}"))
        .collect();
    println!("repeated: {}", repeated.join(", "));
}

It prints:

10 words
a longest word: Some("too")
repeated: cat x2, sat x2, the x2

Step by step:

  • split_whitespace is an iterator over the words of a &str.
  • trim_matches takes the punctuation off both ends of each word, so “sat.” becomes “sat”.
  • filter drops anything that was only punctuation. Our text has none, but text from a user will.
  • to_lowercase makes “The” and “the” the same word. It returns a new String, so words is a Vec<String>.
  • max_by_key finds the item with the biggest key, here the length. When several items tie, it returns the last one, which is why we get “too” and not “the”. The docs say so; it’s easy to assume the first.
  • The counting uses a for loop and the entry API from Part 13. That’s a case where a loop reads better than a fold.
  • The BTreeMap keeps the words in sorted order, so the report is the same on every run.

Tips and traps

  • An adapter with no consumer. v.iter().map(...) on its own line does nothing. The compiler warns “iterators are lazy and do nothing unless consumed”. Add a consumer, or use a for loop if you only wanted the side effects.
  • Too few or too many stars. v.iter().filter(|x| ...) gives the closure &&T. Errors like “can’t compare &&i32 with {integer}” mean you need another *. You can also take the references apart in the pattern: filter(|&&x| x > 2).
  • An iterator is used up. count, sum and collect take the iterator by value. Use it again and you get E0382, “use of moved value”. Call .iter() again to get a fresh one; it’s cheap.
  • collect can’t guess. “type annotations needed” means nothing told collect what to build. Add a type to the variable, or use collect::<Vec<_>>().
  • for x in v moves v. If you need the vector afterwards, loop over &v, or &mut v to change it in place.
  • take_while is not filter. It stops at the first failure and never looks at the rest.
  • Side effects in map. A map that prints or pushes into another vector hides work inside a pipeline, and runs only when something pulls. Use for or for_each for side effects, and keep map for turning one value into another.

An iterator does nothing until something pulls, and then it does just enough to hand over one item.

Exercises

Exercise 1. Use one iterator chain over 1..=10 to compute the sum of the squares of the odd numbers. Print it.

Exercise 2. Without running it, predict every line this program prints:

let found = [3, 8, 5, 12, 7]
    .iter()
    .inspect(|x| println!("looking at {x}"))
    .find(|x| **x > 6);
println!("{found:?}");

inspect calls its closure on each item as it passes through, and changes nothing. It’s made for exactly this kind of peeking.

Exercise 3. Write a struct Fib that implements Iterator and yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, and so on, as u64. Use it with take to print the first 10, and with take_while to sum all the ones below 100.

Answers

1. filter keeps the odd numbers, map squares them, and sum adds them: 1 + 9 + 25 + 49 + 81.

fn main() {
    let total: i32 = (1..=10).filter(|n| n % 2 == 1).map(|n| n * n).sum();
    println!("{total}");
}

It prints:

165

2. find stops at the first match, so 5, 12 and 7 are never looked at. 3 fails, 8 passes, and find returns it.

fn main() {
    let found = [3, 8, 5, 12, 7]
        .iter()
        .inspect(|x| println!("looking at {x}"))
        .find(|x| **x > 6);
    println!("{found:?}");
}

It prints:

looking at 3
looking at 8
Some(8)

3. The struct holds the next two numbers. Each call to next returns the first one and moves both on by one step. The sequence never ends, so next always returns Some; take and take_while are what stop it.

struct Fib {
    a: u64,
    b: u64,
}

impl Fib {
    fn new() -> Fib {
        Fib { a: 0, b: 1 }
    }
}

impl Iterator for Fib {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        let current = self.a;
        self.a = self.b;
        self.b += current;
        Some(current)
    }
}

fn main() {
    let first: Vec<u64> = Fib::new().take(10).collect();
    println!("{first:?}");

    let below_100: u64 = Fib::new().take_while(|n| *n < 100).sum();
    println!("sum below 100: {below_100}");
}

It prints:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
sum below 100: 232

take_while matters here. With filter(|n| *n < 100) instead, the program would never give an answer. filter would keep pulling bigger and bigger numbers, looking for more that pass. In a debug build, self.b += current would overflow after about 90 numbers and panic.

What’s next

Our programs have all lived in one main.rs file. In Part 18, we’ll split code into modules and crates, decide what’s pub, and see how lib.rs, main.rs and workspaces fit together.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.