Sub topic 5
unwrap and expect: shortcuts that can panic
This chapter assumes you know Option<T>, Result<T, E>, and how to handle them with match. You should also know what a closure is.
What unwrap does
unwrap extracts the value inside Some or Ok. If the value is None or Err, the program panics. A panic stops the current thread, prints a message, and by default unwinds the stack.
fn main() {
let some: Option<i32> = Some(5);
println!("{}", some.unwrap());
let port: Result<u16, _> = "8080".parse::<u16>();
println!("{}", port.unwrap());
let none: Option<i32> = None;
println!("{}", none.unwrap());
}The first two calls print 5 and 8080. The third panics with a message like called Option::unwrap() on a None value. The message names the source line, but it does not say why the value was missing.
expect adds a message
expect works like unwrap but takes a message that is included in the panic output.
fn main() {
let home = std::env::var("HOME_DIR_FOR_DEMO")
.expect("HOME_DIR_FOR_DEMO must be set");
println!("{home}");
}If the variable is missing, the panic text starts with your message and then shows the Err value. For a Result, unwrap also prints the error with its Debug format, so you do see the cause. For an Option there is no error value, so the message from expect is the only context you get.
Control flow at a glance
When a panic is acceptable
A panic signals a bug or a state the program cannot recover from. These cases are common and reasonable:
- Tests and examples. A panic fails the test, which is what you want.
- Quick prototypes. You can replace
unwrapwith real handling later. - Proven invariants. You know the value cannot be missing, and
expectdocuments why.
fn main() {
let ip: std::net::IpAddr = "127.0.0.1"
.parse()
.expect("hard-coded address is valid");
println!("{ip}");
}Here the input is a literal in the source. If it fails, the code itself is wrong, so a panic is the right response.
When not to panic
Do not use unwrap on data from users, files, networks, or environment variables. These inputs fail in normal operation. A library that panics on bad input takes away the caller's choice of how to respond. Return a Result instead.
Related methods
| Method | Behavior on `None` or `Err` |
|---|---|
| `unwrap` | Panics with a generic message |
| `expect("msg")` | Panics with your message |
| `unwrap_or(default)` | Returns `default` |
| `unwrap_or_else(f)` | Returns the result of calling `f` |
| `unwrap_or_default()` | Returns `Default::default()` |
The last three never panic. They are covered in the next chapters on combinators.
Writing good expect messages
State what you expected to be true, not what went wrong. The panic already says something went wrong.
fn main() {
let items = vec![3, 1, 2];
// Weak: "list is empty"
// Better: says what the code relied on
let max = items.iter().max().expect("items is built non-empty above");
println!("{max}");
}Exercise
A function reads a port number from a config file and calls .parse::<u16>().unwrap() on the text. Why is this a poor choice, and what should the function return instead?
Show answer
The file content is external input that can be wrong during normal operation, so unwrap would crash the program on a typo. The function should return Result<u16, ParseIntError> (or a custom error type) so the caller decides how to handle the failure.
Exercise
Which is more appropriate for "10.0.0.1".parse::<IpAddr>() where the string is a literal in your source: unwrap, expect("..."), or a match? Explain.
Show answer
expect with a message such as "hard-coded address is valid". The input is fixed, so failure means a programming bug. A panic is acceptable, and the message documents the assumption.