Combine Two Options With Option::zip

Pair two independently parsed values with Option::zip so a missing separator or one failed parse rejects the whole input without nested if-let chains.

RustForm Validation

Code

rustsnippet
24 lines
fn parse_point(spec: &str) -> Option<(f64, f64)> {
    // both sides parse independently: any failure makes the whole thing None
    let (x, y) = spec.split_once(',')?;
    Option::zip(x.trim().parse::<f64>().ok(), y.trim().parse::<f64>().ok())
}

fn main() {
    for spec in ["3.5, 7.25", "1, oops", "42"] {
        match parse_point(spec) {
            Some((x, y)) => println!("\"{spec}\" -> ({x}, {y})"),
            None => println!("\"{spec}\" -> rejected"),
        }
    }

    // compared with hand-written nested unwrapping: zip folds two matches into one line
    let a = Some(10u32);
    let b: Option<u32> = None;
    let manual = match (a, b) {
        (Some(x), Some(y)) => Some((x, y)),
        _ => None,
    };
    println!("manual: {manual:?}");
    println!("zip:    {:?}", Option::zip(Some(10u32), None::<u32>));
}

How the snippet works

Combine Two Options With Option::zip is built around the functions parse_point and main.

Repetition is confined to for spec in ["3.5, 7.25", "1, oops", "42"] — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Applying it

Signature: fn parse_point(spec: &str) -> Option<(f64, f64)>

The demo output is labeled (manual:, zip:), so every printed line maps back to its originating operation.

main sequences parse_point; executing the file runs that flow once.

Statements that matter

fn parse_point(spec: &str) -> Option<(f64, f64)> {
// both sides parse independently: any failure makes the whole thing None
let (x, y) = spec.split_once(',')?;
Option::zip(x.trim().parse::<f64>().ok(), y.trim().parse::<f64>().ok())
}
let manual = match (a, b) {
(Some(x), Some(y)) => Some((x, y)),
_ => None,
};
let b: Option<u32> = None;

Interactive Tools for This Topic

FAQ

What does Combine Two Options With Option::zip print when run?
Run it as a complete program — the output lines carry labels such as `manual:`, `zip:`.