Skip to content
systemcoding.dev
Fundamentals

Convert integers without silent truncation using Rust try_from

Use u8::try_from(x) in Rust to convert integers and get an Err for an out-of-range value, where the as cast would wrap it silently.

1 min read
Summarize in AI

A Rust as cast between integer types always succeeds, and when the value does not fit it silently keeps the low bits. TryFrom is the checked alternative: it returns Ok with the converted value, or an Err carrying TryFromIntError. It is in the prelude from the 2021 edition, and available as std::convert::TryFrom before.

tryfrom.rsrust
fn main() {
    let big: i64 = 300;
    println!("{:?}", u8::try_from(big));
    println!("{}", big as u8);
    println!("{:?}", u8::try_from(200_i64));
    println!("{}", u8::try_from(-1_i32).is_err());
}
Text
Err(TryFromIntError(()))
44
Ok(200)
true

The as line prints 44, which is 300 minus 256, with no warning and no panic. That is the bug class the checked form removes. In a function that returns Result, write let b = u8::try_from(len)?; and let the error propagate. The try_into() method is the same conversion with inference from the target type. The error type carries no value and no message beyond its name, so add context at the call site if you need one. Conversions that cannot fail, like u8 to u32, use From and into() and never need a check. The trait is documented in std::convert::TryFrom.

Taggedrust
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.