Option Combinators Fallback Chain
Resolve layered configuration with Option combinators — map, and_then, or_else, unwrap_or — instead of nested match ladders.
Code
#[derive(Debug)]
struct Config {
timeout_ms: u64,
retries: u32,
}
fn from_env() -> Option<u64> {
// 模拟环境读取:本例固定为 None,走回退链
None
}
fn from_file() -> Option<u64> {
Some(250)
}
fn build_timeout() -> u64 {
from_env()
.or_else(from_file) // 环境没有就取文件
.filter(|&ms| ms >= 50) // 非法值打回
.map(|ms| ms.min(5_000)) // 上限钳制
.unwrap_or(1_000) // 最终默认
}
fn retries_of(raw: Option<&str>) -> u32 {
raw.and_then(|s| s.parse::<u32>().ok())
.filter(|&n| n <= 10)
.unwrap_or(3)
}
fn main() {
let config = Config {
timeout_ms: build_timeout(),
retries: retries_of(Some("15")),
};
println!("{:?}", config);
}How it works
Count the functions from_env, from_file, build_timeout and retries_of as the entire surface area of Option Combinators Fallback Chain.
Applying it
The main signature reads fn from_env() -> Option<u64>
There are 2 calls inside main — build_timeout and retries_of — executed top to bottom.
Statements that matter
fn retries_of(raw: Option<&str>) -> u32 {
raw.and_then(|s| s.parse::<u32>().ok())
.filter(|&n| n <= 10)
.unwrap_or(3)
}
fn from_file() -> Option<u64> {
Some(250)
}
fn from_env() -> Option<u64> {
// 模拟环境读取:本例固定为 None,走回退链
None
}
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
- How do you run Option Combinators Fallback Chain?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.