← 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.
Syntax
rust
let value = result.unwrap();
let value = result.expect("message");
let value = result.unwrap_or(default);

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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `result` (a `Result<i32, String>`), set to `Ok(42)`
    let result: Result<i32, String> = Ok(42);
    // Declare an immutable variable `value`, set to `result.unwrap()`
    let value = result.unwrap();
    // Print "Value: {}" to the console, substituting in `value` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `maybe_value` (a `Option<i32>`), set to `Some(10)`
    let maybe_value: Option<i32> = Some(10);
    // Print "{}" to the console, substituting in `maybe_value.unwrap()` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `config` (a `Option<&str>`), set to `Some("production")`
    let config: Option<&str> = Some("production");
    // Declare an immutable variable `mode`, set to `config.expect("config value must be set")`
    let mode = config.expect("config value must be set");
    // Print "Running in {} mode" to the console, substituting in `mode` (with a trailing newline)
    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
// Define the function `safe_parse` taking `s` and returning an integer
fn safe_parse(s: &str) -> i32 {
    // Match on `s.parse()` and branch by pattern
    match s.parse() {
        Ok(n) => n,
        Err(_) => 0,
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{}" to the console, substituting in `safe_parse("bad input")` (with a trailing newline)
    println!("{}", safe_parse("bad input"));
    // Print "{}" to the console, substituting in `safe_parse("77")` (with a trailing newline)
    println!("{}", safe_parse("77"));
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.