Reacting per error kind in Rust
Matching on an error's variant so each failure gets its own recovery.
use std::num::IntErrorKind;
fn classify(text: &str) -> &'static str {
match text.parse::<u8>() {
Ok(_) => "fits in a byte",
Err(e) => match e.kind() {
IntErrorKind::Empty => "empty input",
IntErrorKind::InvalidDigit => "not a number",
IntErrorKind::PosOverflow => "too large",
_ => "unusable",
},
}
}
fn main() {
for text in ["7", "", "abc", "9000"] {
println!("{text:?}: {}", classify(text));
}
println!("{}", matches!("5".parse::<u8>(), Ok(n) if n > 3));
}
How it works
kind()on an IO error names the category.- Matching lets one branch retry and another give up.
matches!is the terse form when you only need a bool.
Keywords and builtins used here
ErrOkclassifyfnforifinmainmatchstaticstru8use
The run, in numbers
- Lines
- 20
- Characters to type
- 460
- Tokens
- 165
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 94 seconds.
Step 2 of 2 in Panics & recovery, step 14 of 15 in Error handling.