问题描述
在 https://doc.rust-lang.org中/book/primitive-types.html#numeric-types ,它表示为
这意味着x
的默认类型为i32
.
That means x
has the type i32
as default.
但是在 http://rustbyexample.com/cast/literals.html 中,它说那
我知道我不能使用i32
为向量建立索引,但是以下代码可以工作:
I know I can't use i32
to index the vector, but the following code works:
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]);
}
那么,文字整数值的类型是什么?
So, what is the type of a literal integral value?
推荐答案
来自语言参考:
-
如果可以从周围的程序上下文中唯一确定整数类型,则不带后缀的整数文字将具有该类型.
If an integer type can be uniquely determined from the surrounding program context, the unsuffixed integer literal has that type.
如果程序上下文对类型的约束不足,则默认为带符号的32位整数i32
.
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
.
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
.
这篇关于文字整数值在Rust中是否具有特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!