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.In this page:
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
fn main() {
let result: Result<i32, String> = Ok(42);
let value = result.unwrap();
println!("Value: {}", value);
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let maybe_value: Option<i32> = Some(10);
println!("{}", maybe_value.unwrap());
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let config: Option<&str> = Some("production");
let mode = config.expect("config value must be set");
println!("Running in {} mode", mode);
}
Login to try C/C++/Java/PHP code in the editor
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
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"));
}
Login to try C/C++/Java/PHP code in the editor
- Using
.unwrap()in production code paths where a failure is genuinely possible, instead of handling the error gracefully. - Writing a generic panic message via
.unwrap()when.expect("clear message")would make debugging failures much easier. - Assuming
.unwrap()only panics forResult-- it panics forOption::Noneas well.
.unwrap()returns the inner value ofOk/Some, or panics immediately if it isErr/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: