How can I iterate on an Option?

As mentioned in comments to another answer, I would use the following:

// Either one works
foo.people.iter().flatten()
foo.people.iter().flat_map(identity)

The iter method on Option<T> will return an iterator of one or zero elements.

flatten takes each element (in this case &Vec<Person>) and flattens their nested elements.

This is the same as doing flat_map with identity, which takes each element (in this case &Vec<Person>) and flattens their nested elements.

Both paths result in an Iterator<Item = &Person>.

Leave a Comment