std-method

Result::unwrap_or and unwrap_or_else

Recover with a replacement success value. The eager form computes the default before the call; the lazy form receives the error only if Err occurs. Decide whether losing failure information is acceptable. Expected stdout (not executed): 10 Common mistake: Using a silent fallback when a failure must be reported to the caller.

Formal Syntax & Structure

rust syntaxrust
fn unwrap_or(self, default: T) -> T; fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T

Working Example

Example Snippetrust
fn main() {    let parsed = "bad".parse::<u32>();    let value = parsed.unwrap_or_else(|_| 10);    println!("{value}");}
Rust Reference