I want to convert a usize
typed variable into a u32
typed variable in Rust. I am aware that the usize
variable might contain a value larger than 2^32, and in that case the conversion should fail. I am trying to use the TryFrom
trait to perform the conversion.
This is a simple example (Nightly Rust, Playground):
#![feature(try_from)]
use std::convert::TryFrom;
fn main() {
let a: usize = 0x100;
let res = u32::try_from(a);
println!("res = {:?}", res);
}
The code doesn't compile, with the following compilation error:
error[E0277]: the trait bound `u32: std::convert::From<usize>` is not satisfied
--> src/main.rs:6:15
|
6 | let res = u32::try_from(a);
| ^^^^^^^^^^^^^ the trait `std::convert::From<usize>` is not implemented for `u32`
|
= help: the following implementations were found:
<u32 as std::convert::From<std::net::Ipv4Addr>>
<u32 as std::convert::From<u8>>
<u32 as std::convert::From<char>>
<u32 as std::convert::From<u16>>
= note: required because of the requirements on the impl of `std::convert::TryFrom<usize>` for `u32`
I deduce from the compilation error that having TryFrom<usize>
for u32
is dependent on having From<usize>
for u32
, which seems somewhat strange to me.
Is there any other way I could utilize TryFrom
to convert from usize
to u32
? If not, is there any other idiomatic way to perform this conversion?
I know that I can use the as
keyword, but it doesn't notify me if something went wrong with the conversion. In addition, I think that I can write my own function that does the conversion, but I would be surprised if Rust doesn't have some idiomatic way to do this conversion. usize
and u32
are two basic types, after all.