Skip to content
Theory · Errors · lesson 4 of 8

unwrap, expect and unwrap_or

Handling every Result with match is reliable but long. Sometimes you are sure there will be no error, and sometimes a fallback value is enough.

Back to the courier. You can open the package without reading what is written on it. If the parcel is inside, great. If it is a note, your confidence was wrong, and the fire alarm goes off. That is how unwrap works:

Rust
fn main() {
    let a: i32 = "42".parse().unwrap();
    let b = "7".parse::<i32>().unwrap();
    println!("{a} {b}"); // 42 7
}

Let's walk through the example line by line:

  1. "42".parse() returns Ok(42), and unwrap() takes the number out of it.
  2. The type to parse into comes from the notation let a: i32. A type written after a name like this is called a type annotation. The compiler sees that the result must be an i32, so ::<i32> is not needed.
  3. The second line has no annotation, so the type is given right at the method: parse::<i32>(). Both forms are equivalent.
  4. println! prints 42 7: a and b already hold plain numbers, not a Result.

unwrap on Err panics

If there is an Err inside, unwrap panics:

Rust
fn main() {
    let n: i32 = "x".parse().unwrap(); // ✗
    println!("{n}");
}
TEXT
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }

The program builds: the compiler checks types, not the text inside a string. That "x" is not a number turns out only when the program runs. Then parse returns Err, unwrap panics, and println! never runs. The panic message shows the error itself.

unwrap works the same way on an Option: Some(5) gives 5, and None gives the panic called `Option::unwrap()` on a `None` value.

expect panics with an explanation

expect does the same as unwrap, but starts the panic message with your text. For example, "80a".parse::<u16>().expect("port must be a number") fails with the message port must be a number: ParseIntError { kind: InvalidDigit }.

expect is no safer: both panic. It only explains why you believed the error was impossible, and the crash is easier to investigate.

A fallback value: unwrap_or

When a failure has a sensible replacement, use unwrap_or. It gives the value from Ok, and on Err it gives its own argument; it never panics:

Rust
fn main() {
    let a: i32 = "7".parse().unwrap_or(0);
    let b: i32 = "x".parse().unwrap_or(0);
    println!("{a} {b}"); // 7 0
    let bad = "x".parse::<i32>();
    println!("{} {}", bad.is_ok(), bad.is_err()); // false true
}
  1. "7" parses, and a gets 7.
  2. "x" does not parse, and instead of a panic b gets the fallback 0.
  3. is_ok() and is_err() only check the variant and return a bool: the value stays inside.

Here the courier analogy falls short: you can read a courier's note before throwing it away. unwrap_or throws the error away unread, and its cause is lost. If you need the cause, use match.

What to choose

  • unwrap in examples, tests and drafts: there a panic on an error is exactly the behavior you want.
  • expect when the error is impossible by the program's logic, and the text explains why.
  • unwrap_or when a failure has a sensible replacement.
  • match when different errors need different reactions.

Interviewers ask: "Why is unwrap dangerous in production code?" On outside data, such as user input or a file's contents, it turns an expected failure into a crash.

Common mistake

A line read from the keyboard is parsed right away, but it ends with the newline character \n:

Rust
fn parse_answer(line: &str) -> i32 {
    line.parse().unwrap() // ✗
}

fn main() {
    println!("{}", parse_answer("42\n"));
}
TEXT
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }

The program panics, even though the person typed 42. The \n character is extra, and parse needs the whole string to be a number. The fix is to strip spaces and the newline from both ends with trim(): line.trim().parse(). And since the data comes from outside, handle the error with match or use unwrap_or instead of unwrap.

Key points

  • unwrap takes the value out of Ok or Some and panics on Err and None; the compiler does not look inside the string.
  • expect("…") panics the same way but starts the message with your text.
  • unwrap_or(v) never panics: on an error it gives the fallback v.
  • The type for parse comes from an annotation let n: i32 or from parse::<i32>().