Choose fallback values
Quick answer
Sometimes failure or missing data has a meaningful default. Option and Result offer fallback methods, but a default should be an explicit policy rather than a way to hide unexpected errors.
Eager and lazy defaults
unwrap_or(value) evaluates its argument before the method call. unwrap_or_else accepts an anonymous function and computes the fallback only when needed. For Option the function takes no argument; for Result it receives the error. Preserve the error when a default would be misleading.
fn main() { let requested: Option<u32> = None; println!("{}", requested.unwrap_or(1));}Expected stdout (not executed):
1One is the stated default.
fn main() { let value = Some(8); let result = value.unwrap_or_else(|| { println!("fallback"); 3 }); println!("{result}");}Expected stdout (not executed):
8The fallback function is not called.
Common mistake
Do not replace an invalid financial or safety-critical reading with zero without a defined policy.
Try it yourself
Change Some(8) to None and predict both printed lines.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choose fallback values — practice quiz
Choose one answer per question, then review the explanation.
For `Some(5).unwrap_or(9)`, what is returned?
When is the closure in `Some(5).unwrap_or_else(...)` called?
What is the danger of defaulting a malformed required price to zero?