Option and Result

Option and Result, including unwrap panics, the ? operator and its return-type constraint, and parsing with Result.

テーマページの本文は現在英語です。

Option<T> and Result<T, E> are standard-library enum types in the prelude. They are not modules, and they are not a third-party error crate. Option represents a value that may be absent. Result represents a value that may be a failure with an error.

unwrap and expect return the success value or panic. That is sometimes acceptable in a short example or after a check you have already made. In fallible code, match, if let, unwrap_or, and the ? operator make the failure path visible. ? can only be used in a function whose return type can represent that failure, typically Result or Option.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
str::parse and ResultParse text into a typed value and handle Ok and Err explicitly. A failed parse stays a Result; it does not become a silent default.
?, Result::map_err, Option::unwrap, Option::unwrap_or, Option::ok_orPropagate a failure with ? only when the function returns a compatible Result or Option. Use unwrap only when a panic is the intended response to a missing value.

Parse a number with Result

str::parse returns Result. Parsing as u16 checks both syntax and the representable range. Matching on Ok or Err keeps invalid input from turning into a default value unnoticed. A successful u16 parse still does not enforce application rules such as rejecting port 0; those checks belong after parsing.

str::parse and Result

fn parse<F: FromStr>(&self) -> Result<F, F::Err>
enum Result<T, E> {
    Ok(T),
    Err(E),
}

Parse text into a typed value and handle Ok and Err explicitly. A failed parse stays a Result; it does not become a silent default.

ParameterDescription
selfThe input string. parse is a method on str, also available on String through deref.
FThe target type, written with a turbofish such as parse::<u16>().

Returns: Ok(value) when the text is valid for F, otherwise Err with a type-specific error such as std::num::ParseIntError.

  • This example is the original Rust reference recipe; the section id is unchanged.
  • 65536 does not fit in a u16, so it is Err even though it is numeric. The next section shows the error text and an extra application check.
rust
fn main() {
    for input in ["8080", "65536", "oops"] {
        match input.parse::<u16>() {
            Ok(port) => println!("port: {port}"),
            Err(_) => println!("invalid: {input}"),
        }
    }
}

Expected output

port: 8080
invalid: 65536
invalid: oops

Related: Original recipe on the Rust overview, Result

Official documentation →

The ? operator and unwrap

? returns early when the Result is Err (or the Option is None), after converting the error with From. The enclosing function must return a compatible type. You cannot write let port: u16 = input.parse()?; inside fn main() -> () without changing main's return type or handling the Result some other way.

Option::unwrap panics on None. unwrap_or supplies a default without panicking. ok_or turns Option into Result when you want to join an absent value to an error path.

?, Result::map_err, Option::unwrap, Option::unwrap_or, Option::ok_or

// ? in a function returning Result<T, E>
fn unwrap(self) -> T
fn unwrap_or(self, default: T) -> T
fn ok_or<E>(self, err: E) -> Result<T, E>

Propagate a failure with ? only when the function returns a compatible Result or Option. Use unwrap only when a panic is the intended response to a missing value.

ParameterDescription
default / errunwrap_or takes a fallback value of type T. ok_or takes the error to use when the Option is None.

Returns: unwrap returns T or panics. unwrap_or always returns T. ok_or returns Result<T, E>. ? exits the function with the converted error, or yields the success value.

Errors and panics

  • panic — unwrap and expect panic when the Option is None or the Result is Err. The panic message for unwrap is not an error value you can handle with ?.
  • ParseIntError — input.parse::<u16>() fails with a parse error on invalid digits or on a value that does not fit in u16. map_err can turn that error into another type so ? matches the function signature.
  • parse_port returns Result<u16, String>, so ? works after map_err. The check for port 0 is an application rule, not part of parse.
  • The Display text of ParseIntError is shown here as checked on rustc 1.90.0: "number too large to fit in target type" and "invalid digit found in string".
  • A function that returns () cannot use ? on a Result without a From conversion into that return type; there is none for ().
rust
fn parse_port(input: &str) -> Result<u16, String> {
    let port: u16 = input.parse().map_err(|err| format!("{err}"))?;
    if port == 0 {
        return Err("port must not be 0".into());
    }
    Ok(port)
}

fn main() {
    for input in ["8080", "65536", "oops", "0"] {
        match parse_port(input) {
            Ok(port) => println!("port: {port}"),
            Err(err) => println!("invalid {input}: {err}"),
        }
    }

    let missing: Option<i32> = None;
    std::panic::set_hook(Box::new(|_| {}));
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = missing.unwrap();
    }))
    .is_err();
    println!("unwrap none panicked={panicked}");
    println!("unwrap_or={}", missing.unwrap_or(80));
    println!("ok_or={:?}", missing.ok_or("missing"));
}

Expected output

port: 8080
invalid 65536: number too large to fit in target type
invalid oops: invalid digit found in string
invalid 0: port must not be 0
unwrap none panicked=true
unwrap_or=80
ok_or=Err("missing")

Related: The ? operator, Option::unwrap

Official documentation →