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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.