std-method

Option::or_else

Try a secondary lookup only when the primary lookup returns None. Unlike unwrap_or_else, the fallback also returns an Option. Expected stdout (not executed): Some(12) Common mistake: Returning a bare T from the fallback.

Formal Syntax & Structure

rust syntaxrust
fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T>

Working Example

Example Snippetrust
fn main() {    let primary: Option<i32> = None;    println!("{:?}", primary.or_else(|| Some(12)));}
Rust Reference