std-method
Option::map_or / map_or_else
Transform a present quantity or use a fallback of the output type. map_or evaluates its default argument eagerly; map_or_else calls its default closure only for None. Expected stdout (not executed): 15 Common mistake: Expecting map_or to skip calculating its fallback.
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() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> UWorking Example
Example Snippetrust
fn main() { let qty = Some(3); println!("{}", qty.map_or_else(|| 0, |n| n * 5));}