Rust 1.99 (2024 edition) reference · Option and Result
Rust Option::unwrap_or and friends Method
Get the value out of an Option with a default, a computed default, or the type's default instead of panicking with unwrap.
Rust 1.99 (2024 edition)
Syntax
fn unwrap_or(self, default: T) -> T fn unwrap_or_else(self, f: F) -> T fn unwrap_or_default(self) -> T
Parameters
| Parameter | Description |
|---|---|
unwrap_or(v) |
A fixed default (evaluated eagerly). |
unwrap_or_else(|| ...) |
A lazily computed default. |
unwrap_or_default() |
T::default(), e.g. 0 or an empty String. |
expect("msg") |
Panic with a message: for real bugs only. |
Examples
fn expensive_lookup() -> i32 { println!("computing..."); 7 }
fn main() {
let port: Option<u16> = None;
println!("{}", port.unwrap_or(8080));
let name: Option<String> = None;
println!("[{}]", name.unwrap_or_default());
let cached = Some(42);
println!("{}", cached.unwrap_or_else(|| expensive_lookup()));
}
Output
8080 [] 42
Run this on your computer — see “Get Started” for setup.
fn main() {
let env = std::env::var("APP_MODE").ok();
let mode = env.as_deref().unwrap_or("development");
println!("mode: {mode}");
}
Output
mode: development
Run this on your computer — see “Get Started” for setup.
Related
Option::map, and_then and filter· Transform the value inside an Option without unwrapping it, chain optional steps, or keep it only if a condition holds.The ? operator· Propagate errors from functions returning Result or Option: unwrap Ok values and return early on Err.- Rust Enums and Option · tutorial