skip to content

In Rust, what does Option::transpose do to an Option<Result<T, E>>, and why does it suit an optional field that must parse?

level: middleimportance: nice to knowfreq 30%

answer

  1. swap the two wrappers
  2. None stays a success
  3. Some(Err) becomes Err
  4. and_then plus ok() is lossy

basics

~10 s

Option::transpose turns Option<Result<T, E>> into Result<Option<T>, E>: Some(Ok(v)) becomes Ok(Some(v)), Some(Err(e)) becomes Err(e), and None becomes Ok(None). An absent optional field stays a success while a malformed one is an error.

solid answer

~30 s

`Option::transpose` swaps the wrappers: `Some(Ok(v))` becomes `Ok(Some(v))`, `Some(Err(e))` becomes `Err(e)`, and `None` becomes `Ok(None)`. That is exactly the shape of an optional field that must be valid when present. With `age: Option<String>`, `p.age.as_deref().map(|raw| raw.parse::<u32>())` gives `Option<Result<u32, ParseIntError>>`, awkward to handle; `.transpose()` turns it into `Result<Option<u32>, ParseIntError>`, so "not given" is `Ok(None)` and "given but malformed" is `Err`. The common shortcut `and_then(|r| r.parse().ok())` instead folds malformed input into `None`, losing the error. `Result::transpose` goes the other way, `Result<Option<T>, E>` to `Option<Result<T, E>>`, with `Ok(None)` becoming `None`.

code

rust · 28 lines
rust
use std::num::ParseIntError;

struct Profile {
    age: Option<String>, // the age field is optional on the form
}

// None = not provided (fine), Some(Err) = provided but malformed (a failure)
fn parse_age(p: &Profile) -> Result<Option<u32>, ParseIntError> {
    p.age.as_deref().map(|raw| raw.parse::<u32>()).transpose()
}

fn main() {
    let profiles = [
        Profile { age: Some("29".into()) },
        Profile { age: None },
        Profile { age: Some("old".into()) },
    ];
    for p in &profiles {
        match parse_age(p) {
            Ok(Some(age)) => println!("age {age}"),
            Ok(None) => println!("age not given"),
            Err(e) => println!("bad age: {e}"),
        }
    }
    // and back again: Result<Option<T>, E> -> Option<Result<T, E>>
    let back: Option<Result<u32, ParseIntError>> = parse_age(&profiles[1]).transpose();
    println!("{back:?}");
}

go deeper

for a junior

Recall that transpose swaps Option and Result around each other, and that None ends up as Ok(None).

for a middle

Walk the three cases of Option::transpose and show map then transpose on an optional field that must parse.

for a senior

Catch and_then with ok() on fields that must be validated, since it silently accepts malformed input as absent.

for a principal

Agree as a team which optional inputs reject malformed values and which ignore them, and make the code shape show that choice.

## What transpose does `Option<Result<T, E>>` and `Result<Option<T>, E>` hold the same three cases in a different order. `transpose` converts between them: | `Option<Result<T, E>>` | `Option::transpose()` gives | `Result<Option<T>, E>` | |---|---|---| | `Some(Ok(v))` | becomes | `Ok(Some(v))` | | `Some(Err(e))` | becomes | `Err(e)` | | `None` | becomes | `Ok(None)` | `Result::transpose` is the inverse: `Ok(Some(v))` becomes `Some(Ok(v))`, `Err(e)` becomes `Some(Err(e))`, and `Ok(None)` becomes `None`. Both are plain moves of the inner values, with no allocation and no closure. ## The optional-age scenario A user profile has an age field that the form treats as optional: `age: Option<String>`. The rules are: - No age given is fine. - An age given as `"29"` should become `29`. - An age given as `"old"` is a validation failure, and the user should hear why. Mapping the parse over the `Option` produces the wrapping in the wrong order: ```rust let step: Option<Result<u32, ParseIntError>> = p.age.as_deref().map(|raw| raw.parse::<u32>()); let age: Result<Option<u32>, ParseIntError> = step.transpose(); ``` After `transpose`, the outer type is a `Result`, which is the type that error handling works with: a `match` with arms `Ok(Some(age))`, `Ok(None)` and `Err(e)` covers the three rules directly, the value can be returned from a validation function, and it can be propagated by the question-mark operator (that operator's own lesson) to yield a plain `Option<u32>`. ## Why not just and_then and ok() A frequent shortcut is: ```rust let age: Option<u32> = p.age.as_deref().and_then(|r| r.parse().ok()); ``` It compiles and is short, but `ok()` drops the `ParseIntError`, so `"old"` and "not given" both become `None`. The form then silently accepts garbage as "no age". Choose based on the rule: 1. If malformed input must be rejected, use `map` then `transpose`, keeping the error. 2. If malformed input may be ignored as if absent, `and_then` with `ok()` is honest about that choice. 3. If you need both the parsed value and a count of rejects, keep the `Option<Result<..>>` and handle all three cases explicitly. ## The match it replaces Without `transpose`, the same conversion is a two-arm `match` on the optional text: ```rust let age = match p.age.as_deref() { None => Ok(None), Some(raw) => raw.parse::<u32>().map(Some), }; ``` This is a useful way to remember the mapping: `None` has nothing to parse, so it is a success with no value, and `Some(raw)` produces whatever the parse produces, with the success wrapped in `Some`. It also shows a second idiom, `Result::map(Some)`, which wraps the success side of a `Result` in `Some` and leaves the error untouched. Both versions behave the same; `transpose` is shorter and names the intent, while the explicit `match` is clearer when a case needs extra work, such as trimming the input or logging the reject. ## Where transpose shows up - **Optional configuration**: an environment variable that may be unset but must be a valid number when set. - **Iterator steps**: `Result::transpose` turns a fallible step that may find nothing, `Result<Option<T>, E>`, into the `Option<Result<T, E>>` shape an iterator's `next` naturally yields. - **Lookups followed by parsing**: in the user store, the lookup yields an `Option`, the parse a `Result`; `transpose` puts the `Result` outside where error handling expects it. ## Common mistakes - Assuming `None` becomes an `Err`. It becomes `Ok(None)`: absence is still a success after `transpose`. - Writing a nested `match` on `Some(Ok(..))`, `Some(Err(..))` and `None` just to rebuild the `Result` that `transpose` produces in one call. - Using `and_then(|r| r.parse().ok())` for a field that must be validated, silently accepting bad input. - Confusing `transpose` with `flatten`: `flatten` merges two layers of the **same** wrapper, `transpose` swaps two **different** ones.

  • In Rust, what does Result::transpose return for Ok(None)?
    `None`. `Result::transpose` maps `Ok(None)` to `None`, `Ok(Some(v))` to `Some(Ok(v))` and `Err(e)` to `Some(Err(e))`. It is the inverse of `Option::transpose`, and is handy when a fallible step that may find nothing has to feed an iterator, whose `next` returns `Option<Result<T, E>>`.
  • In Rust, when is p.age.as_deref().and_then(|r| r.parse().ok()) an acceptable replacement for map plus transpose?
    When malformed input may honestly be treated as absent, for example an optional display hint you would rather ignore than reject. The `ok()` drops the parse error, so "not given" and "given but invalid" both become `None`. For a field that must be validated, keep the error with `map` then `transpose`.

  • Option::transpose turns None into an Err
  • transpose and flatten do the same thing
  • and_then(|r| r.parse().ok()) reports a malformed optional field as an error
  • Result::transpose maps Ok(None) to Some(Ok(None))
  • transpose needs a closure to decide how to swap the layers