ParseIntError
RustERRORCommonParsing

Cannot parse integer from string

Quick Answer

Trim whitespace and validate input; provide a descriptive error to the user.

What this means

Returned by str::parse::<i32>() (and similar) when the string is not a valid integer representation.

Why it happens
  1. 1Non-digit characters in the string
  2. 2Value out of range for the target type
  3. 3Empty string

Fix

Parse with error context

Parse with error context
let s = "42abc";
match s.trim().parse::<i32>() {
    Ok(n) => println!("{}", n),
    Err(e) => eprintln!("Bad integer '{}': {}", s, e),
}

Why this works

trim() removes surrounding whitespace; the match provides a user-facing message.

Code examples
Triggerrust
"abc".parse::<i32>().unwrap(); // ParseIntError
With ?rust
let n: i32 = "42".parse()?;
Same error in other languages
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors