Let Else Early Exit On Missing Data
Unwrap Option values with let-else so the success path stays flat and missing data exits the branch early instead of nesting matches.
Code
fn parse_ratio(raw: &str) -> Option<f64> {
let (num, den) = raw.split_once('/')?;
let n: f64 = num.trim().parse().ok()?;
let d: f64 = den.trim().parse().ok()?;
if d == 0.0 {
return None;
}
Some(n / d)
}
fn main() {
let rows = ["3 / 4", "1 / 0", "7"];
for row in rows {
// let-else:提取成功则绑定,数据缺失时在 else 提前退出
let Some(ratio) = parse_ratio(row) else {
println!("{} -> unusable", row);
continue;
};
println!("{} -> {:.3}", row, ratio);
}
// if let:只关心一个形态时的轻量匹配
if let Ok(weight) = "82".parse::<i32>() {
println!("weight ok: {}", weight);
}
}How it works
parse_ratio does the parsing with ? chaining — split_once('/'), trim().parse(), plus the d == 0.0 guard — and main feeds it the three rows entries through let-else.
The one repetition in this snippet is the loop for row in rows.
Applying it
fn parse_ratio(raw: &str) -> Option<f64> returns None for a missing /, an unparseable operand, or a zero denominator.
The for row in rows loop prints one line per entry — 3 / 4 -> 0.750 on success, an unusable marker for the zero denominator and the slash-less entry — with weight ok: 82 from the if let block closing the run.
The sequence parse_ratio lives in main; running the file triggers it.
Statements that matter
fn parse_ratio(raw: &str) -> Option<f64> {
let (num, den) = raw.split_once('/')?;
let n: f64 = num.trim().parse().ok()?;
let d: f64 = den.trim().parse().ok()?;
if d == 0.0 {
return None;
}
Some(n / d)
}
let Some(ratio) = parse_ratio(row) else {
println!("{} -> unusable", row);
continue;
};
if let Ok(weight) = "82".parse::<i32>() {
println!("weight ok: {}", weight);
}
Interactive Tools for This Topic
FAQ
- What does Let Else Early Exit On Missing Data print when run?
- The script runs standalone; its 1 labeled outputs include `weight ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.