HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How to idiomatically convert between u32 and usize?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howidiomaticallyandbetweenu32usizeconvert

Problem

This code works and prints "b":

fn main() {
    let s = "abc";
    let ch = s.chars().nth(1).unwrap();
    println!("{}", ch);
}


On the other hand, this code results in a mismatch type error.

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


error[E0308]: mismatched types
--> src/main.rs:5:28
|
5 | let ch = s.chars().nth(n).unwrap();
| ^ expected usize, found u32


For some external reason, I have to use the u32 type for variable n. How can I convert u32 to usize and use it in nth()?

Solution

The as operator works for all number types:

let ch = s.chars().nth(n as usize).unwrap();


Rust forces you to cast integers to make sure you're aware of signedness or overflows.

Integer constants can have a type suffix:

let n = 1u32;


However, note that negative constants, such as -1i32 is internally - 1i32.

Integer variables declared without an explicit type specification are shown as {integer} and will be properly inferred from one of the method calls.

Code Snippets

let ch = s.chars().nth(n as usize).unwrap();
let n = 1u32;

Context

Stack Overflow Q#43704758, score: 61

Revisions (0)

No revisions yet.