Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Result unwrap, expect and unwrap_or

Reference for Rust Result::unwrap, expect, unwrap_or, unwrap_or_else, unwrap_or_default and unwrap_err: extract a value or panic, with safe alternatives.

The unwrap family pulls the value out of a Result. Some members panic when the result is an Err (unwrap, expect); the others supply a fallback instead (unwrap_or, unwrap_or_else, unwrap_or_default). Two more go the other way and expect an error (unwrap_err, expect_err).

A panic in these methods means "this can't fail, and if it does it is a bug". For input you do not control, such as files, user text or network data, prefer a fallback or handle the error with match or ?.

Rust
let n: i32 = "42".parse().unwrap();            // 42
let m: i32 = "oops".parse().unwrap_or(0);      // 0
let k: i32 = "oops".parse().unwrap_or_default(); // 0

Try it

Rust Fallbacks that never panic

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 What a failed unwrap says

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, E> Result<T, E> {
    pub fn unwrap(self) -> T where E: Debug;
    pub fn expect(self, msg: &str) -> T where E: Debug;
    pub fn unwrap_or(self, default: T) -> T;
    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T;
    pub fn unwrap_or_default(self) -> T where T: Default;
    pub fn unwrap_err(self) -> E where T: Debug;
    pub fn expect_err(self, msg: &str) -> E where T: Debug;
}
Method On Ok(v) On Err(e)
unwrap() returns v panics with the Debug text of e
expect(msg) returns v panics with msg followed by the Debug text of e
unwrap_or(d) returns v returns d (evaluated eagerly)
unwrap_or_else(f) returns v returns f(e)
unwrap_or_default() returns v returns T::default()
unwrap_err() panics, showing v returns e
expect_err(msg) panics with msg and v returns e

Panics: unwrap prints a message of the form called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }. expect("port must be a number") prints port must be a number: ParseIntError { kind: InvalidDigit }. Panics exit a standalone program with code 101.

Usage notes

  • Prefer expect over unwrap in code that may panic: the message says which assumption broke. Good messages state the expectation ("config file should exist"), not the failure.
  • unwrap requires E: Debug because it prints the error. A custom error type without Debug can't be unwrapped.
  • unwrap_or(expr) always evaluates expr. If building the default is costly, use unwrap_or_else(|_| expr); for a type's own default use unwrap_or_default().
  • Fine to unwrap: tests, examples, quick prototypes, and values you just proved valid (for example parsing a hard-coded literal). In libraries and long-running services, propagate with ? instead.
  • Clippy: the unwrap_used and expect_used lints (both off by default) let teams ban these in production code.
  • unwrap_unchecked exists but is unsafe and causes undefined behavior on Err. You almost never want it.
  • The Option versions behave the same way but have no error to print; see Option unwrap family.
  • Swallowing an error with unwrap_or(default) hides the reason for the failure. Log it first if it might matter.