134. Iterator::find_map — Find and Transform in One Pass
Looking for the first element that matches and needs to come back as something else? Skip the filter_map(...).next() two-step — find_map says it in one call.
The Problem
You have an iterator and want the first item that satisfies a condition plus the value derived from it. The hand-rolled version is a for loop with a mutable binding and a break:
| |
You can compress it with filter_map(...).next():
| |
It’s shorter, but what you actually mean — find the first one — is buried inside “filter everything, then take one.”
The Fix: find_map
Iterator::find_map takes a closure returning Option<U> and returns the first Some(U) it produces — short-circuiting as soon as the closure says yes:
| |
Same short-circuit behavior as find, but the closure does the transformation too — no separate map step on the result.
Where It Earns Its Keep
Looking up the first input that’s in a small table:
| |
Pulling the first error out of a batch of Results without losing the message:
| |
Anywhere you catch yourself writing .filter_map(...).next() or a manual loop with break, find_map says the same thing with less noise.