How to idiomatically convert between u32 and usize?

The most cautious thing you can do is to use TryFrom and panic when the value cannot fit within a usize:

use std::convert::TryFrom;

fn main() {
    let s = "abc";
    let n: u32 = 1;
    let n_us = usize::try_from(n).unwrap();
    let ch = s.chars().nth(n_us).unwrap();
    println!("{}", ch);
}

By blindly using as, your code will fail in mysterious ways when run on a platform where usize is smaller than 32-bits. For example, some microcontrollers use 16-bit integers as the native size:

fn main() {
    let n: u32 = 0x1_FF_FF;
    // Pretend that `usize` is 16-bit
    let n_us: u16 = n as u16;
    
    println!("{}, {}", n, n_us); // 131071, 65535
}

For broader types of numeric conversion beyond u32 <-> usize, refer to How do I convert between numeric types safely and idiomatically?.

See also:

Leave a Comment