std-method
Option::unwrap_or, unwrap_or_else and unwrap_or_default
Extract the payload or select a fallback. unwrap_or evaluates its argument before the call; unwrap_or_else invokes its closure only for None. unwrap_or_default uses the type’s Default. These consume the Option. Expected stdout (not executed): custom Common mistake: Putting an expensive fallback call inside unwrap_or and expecting lazy evaluation.
Formal Syntax & Structure
rust syntaxrust
fn unwrap_or(self, default: T) -> T; fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T; fn unwrap_or_default(self) -> T where T: DefaultWorking Example
Example Snippetrust
fn main() { let label = Some(String::from("custom")); let text = label.unwrap_or_else(|| { println!("fallback"); String::from("guest") }); println!("{text}");}