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.
Code
#[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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.