typestar

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

  1. kind() on an IO error names the category.
  2. Matching lets one branch retry and another give up.
  3. matches! is the terse form when you only need a bool.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Panics & recovery, step 14 of 15 in Error handling.

← Previous Next →