Rust Reference ยท Option and Result
Option zip, flatten and transpose
Reference for Rust Option::zip, unzip, flatten and transpose: combine two options, remove a nested layer, and swap Option with Result.
When options pile up, a handful of methods rearrange them without a match. zip joins two options into an option of a pair, which is Some only if both were. unzip is the reverse. flatten collapses Option<Option<T>> into Option<T>. transpose swaps the nesting order between Option and Result, turning Option<Result<T, E>> into Result<Option<T>, E>.
These show up most often after map with a closure that itself returns an option or a result, and when parsing an optional input where an absent value is fine but a malformed one is an error.
Some(1).zip(Some("a")); // Some((1, "a")) Some(Some(3)).flatten(); // Some(3) Some("5").map(|s| s.parse::<i32>()).transpose(); // Ok(Some(5))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Option<T> { pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>; } impl<T, U> Option<(T, U)> { pub fn unzip(self) -> (Option<T>, Option<U>); } impl<T> Option<Option<T>> { pub fn flatten(self) -> Option<T>; } impl<T, E> Option<Result<T, E>> { pub fn transpose(self) -> Result<Option<T>, E>; } impl<T, E> Result<Option<T>, E> { pub fn transpose(self) -> Option<Result<T, E>>; }
| Method | Behavior |
|---|---|
zip(other) |
Some((a, b)) if both are Some; otherwise None. |
unzip() |
Some((a, b)) becomes (Some(a), Some(b)); None becomes (None, None). |
flatten() |
Removes exactly one layer: Some(Some(x)) becomes Some(x); Some(None) and None become None. |
transpose() |
None becomes Ok(None); Some(Ok(x)) becomes Ok(Some(x)); Some(Err(e)) becomes Err(e). |
Returns: a new option or result, consuming the receiver.
Panics: none.
Usage notes
flattenremoves one layer only.Some(Some(Some(1)))needs two calls.map(...).flatten()isand_then(...). Preferand_then: it is shorter and says what you mean.transposeis the right tool for "absent is fine, malformed is not". The resultOk(None)means "no input",Ok(Some(v))means "valid input", andErr(e)means "bad input", so a following?handles the error and leaves you an ordinaryOption.ziponly combines two options. For three or more, nest (a.zip(b).zip(c)) or uselet (Some(a), Some(b), Some(c)) = (a, b, c) else { ... };.zip_withis still unstable, so writea.zip(b).map(|(x, y)| ...)instead.- For iterators,
Iterator::flattentreats anOptionas a zero-or-one element iterator, sovec_of_options.into_iter().flatten()collects only theSomevalues. Seefilter_mapandflat_map. - Collecting a whole iterator of
OptionorResultvalues into one is the job ofcollect, nottranspose.