Classify Parse Failures With IntErrorKind

parse errors expose an IntErrorKind: empty input, invalid digits, and overflow each get a distinct case, and NonZero types turn zero into an error.

RustForm Validation

Code

rustsnippet
24 lines
use std::num::IntErrorKind;

fn main() {
    for input in ["42", "", "12a4", "99999999999999999999999"] {
        match input.parse::<i64>() {
            Ok(v) => println!("{input:?} -> ok: {v}"),
            Err(e) => match e.kind() {
                // 每种失败原因一个专属分支,校验提示可精确到字段规则
                IntErrorKind::Empty => println!("{input:?} -> empty string"),
                IntErrorKind::InvalidDigit => println!("{input:?} -> invalid digit"),
                IntErrorKind::PosOverflow => println!("{input:?} -> above i64::MAX"),
                IntErrorKind::NegOverflow => println!("{input:?} -> below i64::MIN"),
                // IntErrorKind 是 non_exhaustive:必须留 wildcard
                other => println!("{input:?} -> {other:?}"),
            },
        }
    }

    // NonZero 类型把 0 当作解析错误:kind 是 IntErrorKind::Zero
    match "0".parse::<std::num::NonZeroI64>() {
        Ok(nz) => println!("nonzero ok: {nz}"),
        Err(e) => println!("zero case: {:?}", e.kind()),
    }
}

Inside the snippet

Everything runnable sits in main, with IntErrorKind doing the classification inside its match.

The loop over ["42", "", "12a4", "99999999999999999999999"] is the only repeated construct. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Using it

Running the file prints labeled results such as nonzero ok:, zero case: — every arm of the IntErrorKind match contributes one line to the run.

Key statements

match "0".parse::<std::num::NonZeroI64>() {
Ok(nz) => println!("nonzero ok: {nz}"),
Err(e) => println!("zero case: {:?}", e.kind()),
}

Interactive Tools for This Topic

FAQ

What does Classify Parse Failures With IntErrorKind print when run?
No setup needed: run the file and look for labeled lines like `nonzero ok:`, `zero case:` in the output.