Skip to main content

How to Unwrap a Result with expect in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

expect takes the value out of a Result or an Option when it's there, and stops the program with your message when it isn't. It suits errors that shouldn't happen, where a clear message is worth more than handling the case.

Syntax​

Syntax
let <value> = <result_or_option>.expect("<message>");
PartWhat it does
<result_or_option>A Result or an Option.
.expect("<message>")Gives back the value inside Ok or Some. On Err or None the program panics: it prints <message> and stops.

The standard library's documentation for Result::expect: "Returns the contained Ok value, consuming the self value." It "Panics if the value is an Err, with a panic message including the passed message, and the content of the Err."

The Example​

The example turns two pieces of text into numbers with parse: "42", which works, and "forty-two", which doesn't.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which parses "42" into n with expect("not a number") and prints it, then parses "forty-two" into m the same way and prints it.

src/main.rs
fn main() {
let n: i32 = "42".parse().expect("not a number");
println!("{n}");

let m: i32 = "forty-two".parse().expect("not a number");
println!("{m}");
}

parse returns a Result: Ok with the number, or Err with a ParseIntError. expect unwraps the first one and panics on the second.

Step 3: Run It​

Terminal
cargo run -q
Output
42

thread 'main' (1667552) panicked at src/main.rs:5:38:
not a number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

A zsh terminal where cargo run -q prints 42, then thread 'main' panicked at src/main.rs:5:38 with not a number: ParseIntError with kind InvalidDigit, and the note about RUST_BACKTRACE=1.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. The first expect gave back 42. The second panicked, and the panic message has three parts:

LineWhat it means
thread 'main' (1667552) panicked at src/main.rs:5:38:The thread that panicked, its operating-system thread ID, which changes on every run, and the file, line and column of the expect call.
not a number: ParseIntError { kind: InvalidDigit }Your message, a colon, and the error inside the Err.
note: run with `RUST_BACKTRACE=1` …Set that environment variable to see the chain of function calls that led there.

The last println! never ran, and the program exited with code 101, the code Rust uses for a panic.

expect or unwrap?​

unwrap() does the same without a message of your own. With "forty-two".parse().unwrap(), the second line of the panic is:

Output
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }

expect is the better habit, because the message says what you expected. The documentation recommends this style: "We recommend that expect messages are used to describe the reason you expect the Result should be Ok."

On an Option, expect panics on None with just your message. names.first().expect("the list is empty") on an empty list printed:

Output
the list is empty

Common Mistakes​

MistakeWhat happensDo this instead
Using expect on input that can really be wrong, such as a user's typingOne bad value stops the whole programHandle the Err with match, or pass it on with ?
A message that repeats the error, such as "error"The panic tells you nothing newSay what you expected: "the config file should exist"
Reading only the messageThe location line already points at the failing callOpen the file at the line and column shown

Troubleshooting​

SymptomLikely causeFix
thread 'main' (…) panicked at src/main.rs:…An expect or unwrap met an Err or NoneFix the input, or handle the error
Exit code 101The program panickedRead the panic message above it

FAQ​

What's the number after 'main'?​

The operating-system ID of the thread that panicked. The standard library prints it from thread::current_os_id(), so it differs on every run: the run above showed 1667552, the next one 1677845.

Is a panic the same as an exception?​

No. The Rust Book's chapter on error handling puts it this way: "Rust doesn’t have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error." expect turns a recoverable error into an unrecoverable one.

Conclusion​

.expect("message") gives you the value inside Ok or Some, and turns an Err or None into a panic with your message, the error and the exact location, exiting with code 101. Keep it for cases that shouldn't happen, and handle real errors with match or ?.

Additional Resources​