Rust Reference ยท Option and Result
Option unwrap, expect and unwrap_or
Reference for Option's unwrap family in Rust: unwrap, expect, unwrap_or, unwrap_or_else, unwrap_or_default and unwrap_unchecked, with panics and when to use each.
The unwrap family takes the value out of an Option<T> and gives you a plain T. They differ in what happens for None: unwrap and expect panic, while unwrap_or, unwrap_or_else and unwrap_or_default supply a replacement value. All of them take the option by value (self), so a non-Copy option is consumed.
Choose by intent. If None would mean a bug, panic with a clear message. If None is a normal case with a sensible fallback, use one of the unwrap_or forms.
let n = Some(4).unwrap_or(0); let s = None::<String>.unwrap_or_default();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Option<T> { pub fn unwrap(self) -> T; pub fn expect(self, msg: &str) -> T; pub fn unwrap_or(self, default: T) -> T; pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T; pub fn unwrap_or_default(self) -> T where T: Default; pub unsafe fn unwrap_unchecked(self) -> T; }
| Method | None behavior |
|---|---|
unwrap() |
Panics with the message "called Option::unwrap() on a None value". |
expect(msg) |
Panics with your message. |
unwrap_or(d) |
Returns d. The argument is always evaluated. |
unwrap_or_else(f) |
Calls f() and returns the result. |
unwrap_or_default() |
Returns T::default() (0, empty string, empty Vec...). |
unwrap_unchecked() |
Undefined behavior. unsafe: only for provably Some. |
Returns: the contained T. Panics: unwrap and expect when the option is None.
Usage notes
expectoverunwrap. A message turns a mysterious panic into a diagnosable one. Phrase it as the expectation ("config must have a port"), not the failure.- Eager versus lazy.
unwrap_or(compute())runscompute()every time. Useunwrap_or_else(compute)when the fallback allocates or does work. Cheap constants are fine withunwrap_or. - Copy and consumption.
Option<i32>isCopy, so you may callunwraprepeatedly.Option<String>is moved; call.as_ref(),.as_deref()or.clone()first if you still need it. - Library code should rarely panic. Prefer returning
OptionorResultand let callers decide. Panicking helpers are fine inmain, tests, and examples. - Option fields in structs:
self.name.as_deref().unwrap_or("unknown")borrows instead of moving. unwrap_uncheckedskips the check for speed; a wrong assumption is undefined behavior, so reach for it only after measuring and with a safety comment.- Clippy warns about
unwrapafter anis_some()test (unnecessary_unwrap); useif letinstead.
Related
Option<T>,mapandand_then,Resultunwrap family,panic!- Lessons: Option basics, Panic, Result