let-else Guards Config Parsing

Parse key-value config lines with let-else so each malformed line diverges into a warning branch while the success path stays flat.

RustConfig Management

Code

snippet
fn parse_port(line: &str) -> Result<u16, String> {
    let Some((key, value)) = line.split_once('=') else {
        return Err(format!("no '=' in {line:?}"));
    };
    if key.trim() != "port" {
        return Err(format!("key is {:?}, not \"port\"", key.trim()));
    }
    value.trim().parse::<u16>().map_err(|e| e.to_string())
}

fn main() {
    for line in ["port=8080", "port=99999", "host=local", "port=abc"] {
        // let-else:模式不匹配走 else 分支,成功绑定留在主路径
        let Ok(port) = parse_port(line) else {
            println!("{line:?} rejected");
            continue;
        };
        // 这里 port 已解包,成功路径不再嵌套 match
        println!("{line:?} accepted: valid port {port}");
    }
}

How it works

parse_port(line: &str) -> Result<u16, String> returns the error text instead of None: a line without = hits let Some((key, value)) = line.split_once('=') else and becomes Err("no '=' in {line:?}"); a wrong key produces an Err naming the key; value.trim().parse::<u16>() maps parse failures to strings via map_err. The inner let-else binds a tuple — both bindings stay on the main path when the pattern matches.

main is the outer let-else: let Ok(port) = parse_port(line) else matches the Result’s Ok variant, sends every Err to the {line:?} rejected branch, and only then reaches println!("... accepted: valid port {port}"). Over ["port=8080", "port=99999", "host=local", "port=abc"] that yields one accepted line and three rejected ones, both paths as flat statements.

What to watch for

  • The else branch must diverge (return, continue, break, panic) — the compiler rejects an else block that falls through.
  • The pattern must match the type: Ok unpacks a Result, Some an Option; mixing them is a compile error.
  • The else branch cannot see the main-path bindings, so rejection messages rely on line itself or the error string parse_port already formatted.

Applying it

The entry-point signature is fn parse_port(line: &str) -> Result<u16, String>

main is the driver: it invokes parse_port before returning.

Statements that matter

let Ok(port) = parse_port(line) else {
    println!("{line:?} rejected");
    continue;
};
fn parse_port(line: &str) -> Result<u16, String> {
    let Some((key, value)) = line.split_once('=') else {
        return Err(format!("no '=' in {line:?}"));
    };
    if key.trim() != "port" {
        return Err(format!("key is {:?}, not \"port\"", key.trim()));
    }
    value.trim().parse::<u16>().map_err(|e| e.to_string())
}

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Through the type system: failures are `Result` variants the caller must consume.
How do you run let-else Guards Config Parsing?
Direct execution is enough; the script has no external requirements.