TryFromIntError
RustERRORCommonType Conversion
Integer conversion out of range
Quick Answer
Use try_from() and handle the error; avoid as casts which silently truncate.
What this means
Returned by TryFrom/TryInto conversions when a numeric value does not fit in the target integer type.
Why it happens
- 1Casting a large i64 to i32 when the value exceeds i32::MAX
- 2Negative value into an unsigned type
Fix
Use try_into() instead of as
Use try_into() instead of as
use std::convert::TryInto; let big: i64 = 300; let small: i32 = big.try_into().map_err(|_| "value too large for i32")?;
Why this works
try_into() returns Err on overflow rather than silently wrapping.
Code examples
Badrust
let x: i32 = 300i64 as i32; // silently wraps
Goodrust
let x: i32 = 300i64.try_into()?;
Sources
Official documentation ↗
Rust std::num
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev