122. Option::filter — Keep Some Only When the Value Passes
You’ve got an Option<T>, but you only want to keep the Some if the value passes a test. The match-with-guard version works — Option::filter says the same thing in one call.
The shape that keeps showing up: parse something into an Option, then validate it. The naive version stacks an if on top of the unwrap:
| |
Option::filter collapses that trailing if into the chain:
| |
Same story for the match-with-guard pattern — when the predicate is the only thing the arm checks, filter reads better:
| |
Two things worth knowing. First, the closure receives &T, not T — same as Iterator::filter. So for Option<i32> you write |&n| n > 0 or |n| *n > 0. For Option<String> auto-deref makes |s| !s.is_empty() just work.
Second, filter only keeps or drops — it never transforms. If the predicate returns true you get the original Some back, untouched. To transform, chain .map() after:
| |
Stable since Rust 1.27, and the kind of method that quietly disappears the boilerplate once you know it’s there.