Lazy Defaults With map_or_else

Split Option handling into two closures with map_or_else so the fallback runs only on None, unlike unwrap_or_else where the default is built first.

RustConfig Management

Code

rustsnippet
34 lines
#[derive(Debug)]
struct Env {
    region: Option<String>,
    replicas: Option<u32>,
}

fn main() {
    let env = Env {
        region: Some("eu-west".into()),
        replicas: None,
    };

    // map_or_else:成功与缺省两条路径各一个闭包
    let region = env
        .region
        .as_deref()
        .map_or_else(|| "unset".to_string(), |r| r.to_uppercase());
    println!("region: {region}");

    // 缺省值是闭包,None 分支才会真正执行
    let mut built = 0;
    let replicas = env.replicas.map_or_else(
        || {
            built += 1;
            3
        },
        |n| n,
    );
    println!("replicas: {replicas} defaults built: {built}");

    // 对照:unwrap_or_else 的缺省闭包同样惰性,但只能处理 Ok/Some 单一形态
    let fallback = env.region.clone().unwrap_or_else(|| "unset".to_string());
    println!("fallback: {fallback}");
}

How the snippet works

Everything happens inside the function main.

What to watch for

  • The imports (if any) point only at standard-library modules.

Applying it

The main signature reads fn main()

Look for the region:, replicas:, fallback: prefixes when the file runs; they tie each line to its step.

Statements that matter

let fallback = env.region.clone().unwrap_or_else(|| "unset".to_string());

Interactive Tools for This Topic

FAQ

What does Lazy Defaults With map_or_else print when run?
Run it as a complete program — the output lines carry labels such as `region:`, `replicas:`, `fallback:`.