Advanced Pattern Matching
Option Destructure
Match Parsed Data
An if let pattern can unpack a successful parse and keep the fallback path explicit.
Program
Play the program to choose raw text and see whether it becomes structured data.
option_destructure.rs
fn main() {
let raw = ;
let parsed = parse_pair(raw);
if let Some((name, count)) = parsed {
println!("{name}={count}");
} else {
println!("invalid");
}
}
fn parse_pair(text: &str) -> Option<(&str, i32)> {
let (name, value) = text.split_once(':')?;
let count = value.parse().ok()?;
Some((name, count))
}
fn main() {
let raw = ;
let parsed = parse_pair(raw);
if let Some((name, count)) = parsed {
println!("{name}={count}");
} else {
println!("invalid");
}
}
fn parse_pair(text: &str) -> Option<(&str, i32)> {
let (name, value) = text.split_once(':')?;
let count = value.parse().ok()?;
Some((name, count))
}
fn main() {
let raw = ;
let parsed = parse_pair(raw);
if let Some((name, count)) = parsed {
println!("{name}={count}");
} else {
println!("invalid");
}
}
fn parse_pair(text: &str) -> Option<(&str, i32)> {
let (name, value) = text.split_once(':')?;
let count = value.parse().ok()?;
Some((name, count))
}
if let
`if let Some((name, count))` handles the success shape directly.
question mark
`?` returns `None` early when splitting or parsing fails.
tuple pattern
`(name, count)` destructures both fields from the successful result.