← Back to Rust Course | Chapter 10: Error Handling | Lesson 3 of 6

unwrap and expect

.unwrap() and .expect() grab the value out of a Result or Option, but they crash the program loudly if there wasn't one.

Using unwrap on Result

.unwrap() extracts the Ok value directly, but immediately panics with a generic message if the Result was actually an Err.

Example: Using unwrap on Result

markup
fn main() {
    let result: Result<i32, String> = Ok(42);
    let value = result.unwrap();
    println!("Value: {}", value);
}

Using unwrap on Option

.unwrap() works the same way on Option, returning the inner value for Some and panicking on None.

Example: Using unwrap on Option

markup
fn main() {
    let maybe_value: Option<i32> = Some(10);
    println!("{}", maybe_value.unwrap());
}

Using expect for Clearer Panics

.expect("message") behaves identically to .unwrap() on success, but on failure it panics with your custom message included, making it much easier to diagnose what went wrong.

Example: Using expect for Clearer Panics

markup
fn main() {
    let config: Option<&str> = Some("production");
    let mode = config.expect("config value must be set");
    println!("Running in {} mode", mode);
}

When to Avoid unwrap in Real Code

Since .unwrap() and .expect() crash the whole program on failure, production code paths that can realistically fail should prefer match, ?, or combinator methods to handle errors gracefully instead.

Example: When to Avoid unwrap in Real Code

markup
fn safe_parse(s: &str) -> i32 {
    match s.parse() {
        Ok(n) => n,
        Err(_) => 0,
    }
}

fn main() {
    println!("{}", safe_parse("bad input"));
    println!("{}", safe_parse("77"));
}
Common Mistakes
  1. Using .unwrap() in production code paths where a failure is genuinely possible, instead of handling the error gracefully.
  2. Writing a generic panic message via .unwrap() when .expect("clear message") would make debugging failures much easier.
  3. Assuming .unwrap() only panics for Result -- it panics for Option::None as well.
Chapter Summary
  • .unwrap() returns the inner value of Ok/Some, or panics immediately if it is Err/None.
  • .expect("message") behaves like .unwrap() but lets you supply a custom panic message for easier debugging.
  • Both are best reserved for cases where failure is truly impossible or acceptable to crash on, such as quick prototypes or tests.
  • Prefer proper error handling (match, ?, or combinators) over .unwrap()/.expect() in real production code paths.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.