Skip to content
Tutorials Center
My learning

Topics

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.

Rust
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

Rust zip, unzip and flatten

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.

Rust transpose for optional input

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

Rust
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

  • flatten removes one layer only. Some(Some(Some(1))) needs two calls.
  • map(...).flatten() is and_then(...). Prefer and_then: it is shorter and says what you mean.
  • transpose is the right tool for "absent is fine, malformed is not". The result Ok(None) means "no input", Ok(Some(v)) means "valid input", and Err(e) means "bad input", so a following ? handles the error and leaves you an ordinary Option.
  • zip only combines two options. For three or more, nest (a.zip(b).zip(c)) or use let (Some(a), Some(b), Some(c)) = (a, b, c) else { ... };.
  • zip_with is still unstable, so write a.zip(b).map(|(x, y)| ...) instead.
  • For iterators, Iterator::flatten treats an Option as a zero-or-one element iterator, so vec_of_options.into_iter().flatten() collects only the Some values. See filter_map and flat_map.
  • Collecting a whole iterator of Option or Result values into one is the job of collect, not transpose.