Editor's note: This question is from a version of Rust prior to 1.0 and references some items that are not present in Rust 1.0. The answers still contain valuable information.
What's the idiomatic way to convert from (say) a usize
to a u32
?
For example, casting using 4294967295us as u32
works and the Rust 0.12 reference docs on type casting say
A numeric value can be cast to any numeric type. A raw pointer value can be cast to or from any integral type or raw pointer type. Any other cast is unsupported and will fail to compile.
but 4294967296us as u32
will silently overflow and give a result of 0.
I found ToPrimitive
and FromPrimitive
which provide nice functions like to_u32() -> Option<u32>
, but they're marked as unstable:
#[unstable(feature = "core", reason = "trait is likely to be removed")]
What's the idiomatic (and safe) way to convert between numeric (and pointer) types?
The platform-dependent size of isize
/ usize
is one reason why I'm asking this question - the original scenario was I wanted to convert from u32
to usize
so I could represent a tree in a Vec<u32>
(e.g. let t = Vec![0u32, 0u32, 1u32]
, then to get the grand-parent of node 2 would be t[t[2us] as usize]
), and I wondered how it would fail if usize
was less than 32 bits.