std-method

Result::map_or / map_or_else

Convert either branch to a common output type. The lazy fallback receives the error value. map_or evaluates its default argument eagerly. Expected stdout (not executed): 0 Common mistake: Using a fallback that conceals a failure which needs reporting.

Formal Syntax & Structure

rust syntaxrust
fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U; fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U

Working Example

Example Snippetrust
fn main() {    let value = "oops".parse::<u32>().map_or_else(|_| 0, |n| n * 2);    println!("{value}");}
Rust Reference