skip to content

In Rust, when a `filter` then `map` chain ends in `find`, in what order do the closures run and how many log lines are processed?

level: middleimportance: should knowfreq 58%

answer

  1. pull, not stage by stage
  2. one item through the chain
  3. stops at the first match
  4. later lines never read

basics

~20 s

Item by item: find pulls one line, filter tests it, and only a line that passes reaches map before the next line is pulled. find returns at the first match, so the lines after it are never read by any closure.

solid answer

~40 s

A Rust chain is pull-driven, not stage by stage. `find` calls `next` on the outer `Map`, which calls `next` on the `Filter`, which pulls lines until its predicate returns `true`; `Map` then transforms that single line and hands it to `find`'s predicate. So the prints interleave: filter, filter, map, and so on. The moment `find`'s predicate returns `true`, it returns `Some(item)` and nothing else is pulled — with four lines and the first error matching, two filter calls and one map call run, and the last two lines are never touched. `any`, `all`, `position` and `try_fold` stop early the same way. `take_while` ends the chain at its first `false`, but it has already consumed that element, so it is lost to any later use of the source.

code

rust · 17 lines
rust
fn main() {
    let lines = ["INFO web 200", "ERROR auth 500", "ERROR web 503", "INFO db 200"];

    let first = lines
        .iter()
        .filter(|l| {
            println!("filter {l}");
            l.starts_with("ERROR")
        })
        .map(|l| {
            println!("map    {l}");
            l.rsplit(' ').next().unwrap()
        })
        .find(|code| code.starts_with('5'));

    println!("{first:?}");
}

go deeper

for a junior

Know that items flow one at a time through the chain and that find, any and all stop as soon as they have an answer.

for a middle

Trace a chain call by call, predict interleaved output from side effects, and name which consumers short-circuit and which always run to None.

for a senior

Spot the bugs pull order causes: side effects skipped by early exit, counters read mid-stream, and the element take_while silently consumes. Order cheap filters before expensive maps.

for a principal

Encourage side-effect-free closures in iterator chains as a team norm, so evaluation order and early exit never change program behaviour.

## Pull-based evaluation Rust iterator adapters are **lazy** and **pull-based**. A chain like `lines.iter().filter(p).map(f).find(q)` does not run `filter` over every line, then `map` over the survivors, then `find`. Instead, the consumer at the end asks for one item at a time: 1. `find` calls `Map::next`. 2. `Map::next` calls `Filter::next`. 3. `Filter::next` calls the slice iterator's `next` repeatedly, running `p` on each line, until `p` returns `true` or the source is empty. 4. `Map` applies `f` to that one line and returns the result. 5. `find` runs `q` on it; if `q` is `true` it returns `Some(item)` immediately, otherwise it goes back to step 1. Every item makes the full trip before the next item starts. This is why you never see an intermediate collection, and why side effects in different closures **interleave**. ## Tracing the log analyser Given four lines — an `INFO`, two `ERROR`s with 5xx codes, another `INFO` — and a `println!` in each closure, the program prints: ```plaintext filter INFO web 200 filter ERROR auth 500 map ERROR auth 500 Some("500") ``` - `filter` ran twice: it rejected the first line and accepted the second. - `map` ran once, only for the accepted line. - `find`'s predicate matched `"500"`, so it returned. - The third and fourth lines were never read by anything. An eager, stage-by-stage design would have filtered four lines and mapped two. The difference matters when `f` is expensive (a regex, a parse, a lookup) or has side effects (a log line, a counter). ## Which consumers stop early | Consumer | Stops when | Returns | |---|---|---| | `find(p)` | `p(&item)` is `true` | `Some(item)` or `None` | | `any(p)` | `p(item)` is `true` | `true`, else `false` at the end | | `all(p)` | `p(item)` is `false` | `false`, else `true` at the end | | `position(p)` | `p(item)` is `true` | `Some(index)` or `None` | | `try_fold(init, f)` | `f` returns `None`, `Err` or `ControlFlow::Break` | that value | | `count`, `fold`, and `collect` or `sum` into plain types | only at `None` | the full result | In std, `any` and `find` are written on top of `try_fold`, which is the general early-exit consumer. `find`, `any`, `all`, `position` and `try_fold` take `&mut self`, so after an early stop the iterator is still usable: the items after the match are still there to be pulled. ## Adapters that end a chain early Some adapters also cut the stream short, and each has an edge worth knowing: - **`take_while(p)`** yields items while `p` is `true` and ends at the first `false`. To see that `false`, it had to pull the element — and it does not put it back. With `it.by_ref().take_while(|&n| n != 3)` over `[1, 2, 3, 4]`, the `3` is gone and `it.next()` afterwards gives `Some(4)`. - **`take(n)`** stops after `n` items; it is how an infinite source such as `(1..)` becomes finite. - **`zip`** ends as soon as either side returns `None`. Its general implementation pulls from the first iterator before the second, so when the second side runs out first, one more item may already have been taken from the first side and dropped. - **`skip_while`** is the opposite of `take_while`: it discards a prefix while the predicate holds, then yields everything after it, including later items the predicate would have skipped. ## Practical consequences - Never rely on one stage having seen every element before the next stage runs; a counter incremented in `filter` and read inside `map` sees a running value, not a total. - Put the cheap test first: a `filter` before an expensive `map` means the expensive closure runs only on survivors, and only until the consumer is satisfied. - Expect short-circuiting consumers to leave closures un-run. Code that depends on a side effect in every element should use `for_each` or a `for` loop, not `any` or `find`. - When you need the element `take_while` rejected, use `Peekable::next_if` or restructure the loop (custom iterator adapters are covered with custom sequence types). - Use early exit deliberately: `lines.iter().any(|l| l.contains("FATAL"))` reads only as far as the first fatal line, which on a large log file is the difference between scanning a few kilobytes and scanning everything. ## Why order is predictable Pull order is not an optimiser accident; it follows from the `Iterator` contract itself. Each adapter's `next` is ordinary code that calls its inner `next` and applies its closure, so the interleaving you see in a debug build is the interleaving you get in release. What the optimiser may do is fuse those calls into one loop — it never reorders observable side effects such as `println!`.

  • After `let head: Vec<_> = it.by_ref().take_while(|&n| n != 3).collect();` over `[1, 2, 3, 4]`, where did the `3` go?
    It was consumed and dropped. `take_while` must pull an element to test it; when the predicate returns `false` it ends iteration without storing that element. `head` is `[1, 2]`, and `it.next()` returns `Some(4)`. std's own documentation calls this out.
  • Is the iterator still usable after `any` returns `true`?
    Yes. `any`, `all`, `find` and `position` take `&mut self`, so the caller keeps the iterator, and the elements after the one that ended the search are still there. For `[1, 2, 3]`, `it.any(|x| x == 2)` returns `true` and the next call to `it.next()` gives `Some(3)`.

  • filter runs over every line first, then map runs on the filtered list
  • find evaluates the whole chain and then picks the first match
  • take_while puts back the element that failed its predicate
  • A closure cannot stop iteration, so early exit needs a for loop with break
  • any consumes the iterator, so the remaining items are lost