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

标签 rust literals

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 类型。

关于rust - 文字整数值在 Rust 中是否具有特定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38854408/

相关文章:

json - 同时支持 serde_json::Value 和 cbor_json::Value

命名组匹配的正则表达式数组

syntax - 为什么我不能声明一个带有元组参数匹配的特征函数?

rust - 为什么在我为 Vec<T> 添加实现后 Rust 编译器不使用预期的特征实现?

c++ - 文字的使用,在 C++ 中是/否

c++ - 空指针常量(nullptr)、空指针值和空成员指针值之间有什么区别?

c++ - 为什么 "0xe+1"无法编译?

rust - 在 Rust 中使用多个 .c 源文件

c - 将字符串文字分配给 char 数组,字符串文字如何复制到堆栈上?

javascript - 如何在javascript中检查对象中是否存在键