API Boundaries · 16 min · free lesson

Compose Optional Fallible Input

Keep missing configuration distinct from a configuration that is present but invalid.

Core idea

Apply defaults to absence, not to every failure.

Diagram for Compose Optional Fallible Input: a Rust code example flows to the lesson rule and the key observation.
map, transpose, and explicit defaults

Understand it

An optional configuration value can have three outcomes: no value was supplied, a valid value was supplied, or an invalid value was supplied. Result<Option<T>, E> preserves those outcomes. Converting an error into None with ok() loses the distinction, and adding unwrap_or too early can make a typo look like a deliberate default.

Map a parser over Option<&str> and the intermediate type becomes Option<Result<T, E>>. transpose() changes that nesting into Result<Option<T>, E>. It does not run the parser for None, hide an error, or pick a default. A match expression can implement the same behavior and may be easier while learning; combinators are useful when they keep the boundary readable.

The exercise accepts an optional nonzero u16 port. None stays Ok(None). Some text is trimmed, parsed, and validated using the same policy as the previous lesson. Some empty text is an invalid supplied value, not absence. That distinction matters for environment variables, web forms, and configuration merging, where an explicit invalid override should not silently fall back to an older value.

Local compiler profile: standard library only. Verify absent input, valid text, blank text, zero, and overflow separately. After the conversion succeeds, the application can deliberately choose port.unwrap_or(default_port). Keep that policy outside the parser so another caller can require a value instead. Error-preserving composition is more important than making a chain of adapters as short as possible.

Read the code

fn main() {
    let input = Some("42");
    let parsed: Result<Option<u16>, _> =
        input.map(str::parse::<u16>).transpose();
    assert_eq!(parsed, Ok(Some(42)));
    let absent: Option<&str> = None;
    assert_eq!(
        absent.map(str::parse::<u16>).transpose(),
        Ok(None)
    );
}

map, transpose, and explicit defaults

Try it

Preserve None as Ok(None). For supplied text use the preceding port policy: zero is a zero error, bad syntax/overflow is invalid, and nonzero u16 becomes Ok(Some(n)). In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

What is the type after transposing Option<Result<u16, E>>?

Reveal the answer
  1. Result<Option<u16>, E>
  2. Option<u16>, with every error removed
  3. Result<u16, Option<E>>

Transpose preserves absence and errors while moving Result to the outside.

Go deeper

Common misconception: An invalid supplied value should always become the default.

A default is a policy for absence; invalid input often needs to be reported.

  1. Absent: None does not invoke the parser.
  2. Present: Some text invokes the same checked parser as required input.
  3. Compose: Transpose preserves the error and lets the caller choose a default later.

Transfer challenge: Implement the same function with match and with map/transpose; compare behavior on blank text and absent input.

Connections

  • FromStr & Domain Values: A validated constructor behind a parsing trait
  • Flexible Borrowed Inputs: AsRef without unnecessary ownership