How to Use Closures for Lazy Evaluation in Rust

Use closures with methods like unwrap_or_else to defer expensive computations until the value is actually needed.

Use a closure with unwrap_or_else to defer expensive computation until the value is actually needed. This pattern ensures the closure body only executes if the Option is None, achieving lazy evaluation.

let result: Option<i32> = None;
let value = result.unwrap_or_else(|| {
    println!("Computing...");
    42
});

In this example, println! only runs if result is None. If result were Some(10), the closure would never execute.