std-type

ParseIntError and IntErrorKind

Distinguish malformed text from an integer that is too large, without parsing a diagnostic message. Match error kinds with a fallback for future variants. Expected stdout (not executed): invalid digit too large empty Common mistake: Matching human-readable error text or omitting the wildcard for a non-exhaustive enum.

Formal Syntax & Structure

rust syntaxrust
text.parse::<u8>(); error.kind()

Working Example

Example Snippetrust
fn main() {    use std::num::IntErrorKind;    for text in ["bad", "300", ""] {        let err = text.parse::<u8>().unwrap_err();        let reason = match err.kind() {            IntErrorKind::InvalidDigit => "invalid digit",            IntErrorKind::PosOverflow => "too large",            IntErrorKind::Empty => "empty",            _ => "other",        };        println!("{reason}");    }}
Rust Reference