Sub topic 5
unwrap and expect: shortcuts that can panic
This chapter assumes you know Option and Result, match, and the basics of ownership. By the end you should be able to explain what unwrap and expect do, what a panic costs, and when each shortcut is acceptable.
What unwrap and expect do
unwrap and expect extract the value inside an Option<T> or Result<T, E>. If the value is there, you get the T. If it isn't, the thread panics.
| Method | On `Some(v)` / `Ok(v)` | On `None` | On `Err(e)` |
|---|---|---|---|
| `unwrap()` | returns `v` | panics with a fixed message | panics, printing `e` with `{:?}` |
| `expect(msg)` | returns `v` | panics with `msg` | panics with `msg: ` followed by `e` in `{:?}` form |
fn main() {
let a: Option<i32> = Some(5);
println!("{}", a.unwrap());
let b = "8080".parse::<u16>();
println!("{}", b.unwrap());
let c: Option<i32> = None;
println!("{}", c.unwrap());
}The first two lines print 5 and 8080. The last call panics, and the program prints a message like this to standard error:
thread 'main' panicked at src/main.rs:9:22:
called `Option::unwrap()` on a `None` valueFor a Result, the message includes the error value. For example, "abc".parse::<u16>().unwrap() reports `called Result::unwrap() on an Err value: ParseIntError { kind: InvalidDigit }`.
Because unwrap prints the error with Debug, Result::unwrap requires E: Debug. Option::unwrap has no such bound. The reverse methods unwrap_err and expect_err panic when the value is Ok. They need T: Debug and are mostly used in tests.
What a panic does
A panic is not an exception you are expected to catch. It signals a bug: the program reached a state its author believed impossible. By default it does the following:
- It prints the message and location to standard error.
- It unwinds the stack of the panicking thread, running
Dropimplementations on the way. - If that thread is
main, the process exits with code 101. A panic in another thread ends only that thread, and the panic is reported to whoever callsjoin.
Setting RUST_BACKTRACE=1 adds a backtrace to the output. Setting panic = "abort" in a Cargo profile skips unwinding and aborts the process immediately. That makes binaries smaller, but destructors no longer run.
Rust does have std::panic::catch_unwind, but it is not a general error-handling tool. Library code should return Result for failures a caller might reasonably want to handle.
expect: unwrap with a reason
expect behaves like unwrap but lets you attach a message. The message should say why you believed the value could not be missing. It should not just restate that something failed.
use std::net::SocketAddr;
fn main() {
let addr: SocketAddr = "127.0.0.1:8080"
.parse()
.expect("hard-coded address is valid");
println!("{addr}");
}If someone later edits the literal and breaks it, the panic message points straight at the broken assumption. Compare these two messages:
- Weak:
expect("failed to parse"). This repeats what the panic already tells you. - Better:
expect("hard-coded address is valid"). This states the invariant that was violated.
When a shortcut is acceptable
Panicking is reasonable when failure means a programmer error rather than a runtime condition. Common cases:
- Tests and examples. A panic fails the test, which is the point.
assert_eq!("42".parse::<i32>().unwrap(), 42)is idiomatic. - Prototypes. Quick scripts and spikes where you will replace the shortcuts before shipping.
- Proven invariants. Cases the compiler cannot see but you can prove, such as parsing a literal, or taking the first element of a
Vecyou just filled. - Startup. Failing fast when required configuration is missing can be better than limping on. Even then, returning an error from
mainusually gives a cleaner message (a later chapter covers this).
It is not acceptable when the failure depends on user input, files, the network, the environment, or anything else outside your program's control. Those failures are expected, so they should be values. A server that panics on a malformed request lets any client crash it.
Non-panicking alternatives
Most uses of unwrap in production code can become one of these:
fn main() {
let input = "x";
let a = input.parse::<i32>().unwrap_or(0);
let b = input.parse::<i32>().unwrap_or_else(|e| {
eprintln!("bad input: {e}");
-1
});
let c: i32 = input.parse().unwrap_or_default();
println!("{a} {b} {c}");
}This prints bad input: invalid digit found in string to standard error, then 0 -1 0 to standard output.
unwrap_or(default)evaluatesdefaulteagerly, even when the value is present. Use it for cheap values.unwrap_or_else(f)callsfonly onNoneorErr. On aResult,freceives the error. Use it when the default is expensive to build or when you want to log.unwrap_or_default()usesDefault::default()forT.
Common mistakes
Checking, then unwrapping. This pattern is legal but redundant, and a later edit can separate the check from the unwrap:
fn describe(v: Option<&str>) -> String {
if v.is_some() {
format!("got {}", v.unwrap())
} else {
String::from("nothing")
}
}
fn describe_better(v: Option<&str>) -> String {
match v {
Some(text) => format!("got {text}"),
None => String::from("nothing"),
}
}
fn main() {
println!("{}", describe(Some("a")));
println!("{}", describe_better(None));
}The match version cannot panic. The compiler guarantees that text exists exactly where you use it.
Unwrapping on a borrowed value. unwrap takes self by value, so calling it on an Option<String> you still need moves the contents out. Use as_ref() first when you only want to look. A later chapter covers this.
Hiding a panic in a helper. A function that calls unwrap internally has a panic in its behavior, but its signature does not show it. If a function can fail for reasons the caller controls, return Result. If it panics on purpose, document it in a # Panics section of its doc comment, as the standard library does.
Using unwrap where ? fits. If the enclosing function already returns Result or Option, writing ? propagates the failure instead of crashing. The next chapters cover this.
Auditing a codebase
Clippy has opt-in lints, clippy::unwrap_used and clippy::expect_used, that flag every call. Enabling them in a library crate turns accidental panics into review items. You can still allow specific calls with #[allow(clippy::expect_used)] plus a comment explaining the invariant.
Exercise
A web handler reads a ?page= query parameter and runs let page: u32 = query.get("page").unwrap().parse().unwrap();. Name two distinct ways this can panic. Then rewrite the line so a missing or invalid value falls back to page 1. Assume query is a HashMap<String, String>.
Show answer
It panics if the page key is missing (the first unwrap sees None) and if the value is not a valid u32 (the second unwrap sees Err). Both depend on client input. One fix is let page: u32 = query.get("page").and_then(|s| s.parse().ok()).unwrap_or(1);. The and_then call turns a parse failure into None, and unwrap_or(1) supplies the default.
Exercise
Which of these expect calls is justified, and why? (a) File::open(user_path).expect("open failed") (b) Regex::new(r"^\d+$").expect("regex literal is valid")
Show answer
(b) is justified. The pattern is a literal fixed at compile time, so a failure means a programmer error, and the message states the invariant. (a) depends on a user-supplied path, so failure is an expected runtime condition. It should return or handle an io::Error. Its message also says nothing useful.