patterns/idioms/option-iter.md
Andrew Sonin 482c2b8720
Fix typo (#300)
`Iterator::filter_map` is analogous to `Iterator::map`, not `Iterator::flat_map`
2022-03-09 09:08:25 +01:00

2.0 KiB

Iterating over an Option

Description

Option can be viewed as a container that contains either zero or one element. In particular, it implements the IntoIterator trait, and as such can be used with generic code that needs such a type.

Examples

Since Option implements IntoIterator, it can be used as an argument to .extend():

let turing = Some("Turing");
let mut logicians = vec!["Curry", "Kleene", "Markov"];

logicians.extend(turing);

// equivalent to
if let Some(turing_inner) = turing {
    logicians.push(turing_inner);
}

If you need to tack an Option to the end of an existing iterator, you can pass it to .chain():

let turing = Some("Turing");
let logicians = vec!["Curry", "Kleene", "Markov"];

for logician in logicians.iter().chain(turing.iter()) {
    println!("{} is a logician", logician);
}

Note that if the Option is always Some, then it is more idiomatic to use std::iter::once on the element instead.

Also, since Option implements IntoIterator, it's possible to iterate over it using a for loop. This is equivalent to matching it with if let Some(..), and in most cases you should prefer the latter.

See also