Do literal integral values have a specific type in Rust?

前端 未结 1 677
我在风中等你
我在风中等你 2020-12-19 09:58

In https://doc.rust-lang.org/book/primitive-types.html#numeric-types, it said that in

let x = 42; // x has type i32

That means

相关标签:
1条回答
  • 2020-12-19 10:38

    From the language reference:

    The type of an unsuffixed integer literal is determined by type inference:

    • If an integer type can be uniquely determined from the surrounding program context, the unsuffixed integer literal has that type.

    • If the program context under-constrains the type, it defaults to the signed 32-bit integer i32.

    • If the program context over-constrains the type, it is considered a static type error.

    On the line

    println!("{}", v[1]); // is 1 a usize?
    

    the surrounding program context requires 1 to be an usize (because that's what the [] operator needs), so yes, here 1 will have the type usize.

    0 讨论(0)
提交回复
热议问题