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:
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:
"42".parse()returnsOk(42), andunwrap()takes the number out of it.- 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 ani32, so::<i32>is not needed. - The second line has no annotation, so the type is given right at the method:
parse::<i32>(). Both forms are equivalent. println!prints42 7:aandbalready hold plain numbers, not aResult.
unwrap on Err panics
If there is an Err inside, unwrap panics:
fn main() {
let n: i32 = "x".parse().unwrap(); // ✗
println!("{n}");
}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:
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
}"7"parses, andagets7."x"does not parse, and instead of a panicbgets the fallback0.is_ok()andis_err()only check the variant and return abool: 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
unwrapin examples, tests and drafts: there a panic on an error is exactly the behavior you want.expectwhen the error is impossible by the program's logic, and the text explains why.unwrap_orwhen a failure has a sensible replacement.matchwhen 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:
fn parse_answer(line: &str) -> i32 {
line.parse().unwrap() // ✗
}
fn main() {
println!("{}", parse_answer("42\n"));
}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
unwraptakes the value out ofOkorSomeand panics onErrandNone; 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 fallbackv.- The type for
parsecomes from an annotationlet n: i32or fromparse::<i32>().