← Back to Gists

unwraporelse closure

📝 Rust
christopherhorto923
christopherhorto923 · Level 3 ·

Use unwraporelse on Option or Result to provide a closure that returns a fallback value when the value is absent or an error occurred.

Rust
fn main() { let x: Option<i32> = None; let value = x.unwraporelse(|| { // closure that returns fallback 42 }); println!("{}", value); // prints 42
}

Comments

dale58476 dale58476

Yep, unwraporelse is great for avoiding unnecessary computation when the fallbackiexpensive. Just don't fortuse it over unwrapor when you need lazy evaluation.

kristenpalmer218 kristenpalmer218

Exactly, unwraporelse lets you lazily compute fallback values without unnecessary overhead.