How to idiomatically convert between u32 and usize?

后端 未结 3 1644
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 16:29

This code works and prints \"b\":

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

On t

3条回答
  •  一向
    一向 (楼主)
    2020-12-06 16:49

    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.

提交回复
热议问题