typestar

Between Option and Result in Rust

The two conversions worth memorising: ok_or adds an error, ok drops one.

fn first_word(line: &str) -> Result<&str, &'static str> {
    line.split_whitespace().next().ok_or("empty line")
}

fn main() {
    println!("{:?}", first_word("hello there"));
    println!("{:?}", first_word("   "));

    let parsed: Option<i32> = "12".parse().ok();
    println!("{:?}", parsed);

    let nested: Result<Option<i32>, std::num::ParseIntError> =
        Some("5").map(|s| s.parse()).transpose();
    println!("{:?}", nested);
}

How it works

  1. ok_or turns None into an Err you choose.
  2. ok throws the error away and keeps a Option.
  3. transpose swaps a nested Option and Result.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
407
Tokens
148
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 93 seconds.

Type this snippet

Step 3 of 3 in Option, step 3 of 15 in Error handling.

← Previous Next →