Option Combinators Fallback Chain

Resolve layered configuration with Option combinators — map, and_then, or_else, unwrap_or — instead of nested match ladders.

RustConfig Management

Code

rustsnippet
36 lines
#[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

FAQ

How do you run Option Combinators Fallback Chain?
Just run the file; everything it needs ships with the runtime itself.