文字整数值在 Rust 中是否具有特定类型?

Do literal integral values have a specific type in Rust?

https://doc.rust-lang.org/book/primitive-types.html#numeric-types中表示在

let x = 42; // x has type i32

这意味着 x 的默认类型为 i32

但是在http://rustbyexample.com/cast/literals.html中,它说

Unsuffixed literal, their types depend on how they are used

我知道我不能使用 i32 来索引向量,但下面的代码有效:

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let j = 1;  // j has default type i32? or it has type when it is first used?
                // And what is the type of 1?

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

那么,文字整数值的类型是什么?

来自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.

在线

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

周围的程序上下文要求 1 是 usize(因为这是 [] 运算符所需要的),所以是的,这里的 1 将具有类型 usize.