Rust signed integer to unsigned integer checked casting

Hi, all.

Let's say I have an i32, but it might be negative, how could I perform a checked casting to u32? So that I could know an i32 can be safely cast to an u32.

Is there any simple and idiomatic way to do this?

You can use TryFrom.

dbg!(u32::try_from(i32::MAX));
dbg!(u32::try_from(-42));
4 Likes

In addition to try_from, there is also try_into:

let i: i32 = -3;
let u: u32 = match i32::try_into(i) {
    Ok(u32) => u32,
    Err(e) => 0,        // default value
};

To check if a signed int i is negative, you can use the i.is_negative() method or simply use i < 0.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.