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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.