文字整数值在Rust中是否具有特定类型? [英] Do literal integral values have a specific type in Rust?

查看:90
本文介绍了文字整数值在Rust中是否具有特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

让x = 42; //x的类型为i32

let x = 42; // x has type i32

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

That means x has the type i32 as default.

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

后缀文字,它们的类型取决于它们的使用方式

Unsuffixed literal, their types depend on how they are used

我知道我不能使用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?

推荐答案

来自

无后缀整数文字的类型由类型决定 推论:

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.

如果程序上下文对类型的约束不足,则默认为带符号的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中是否具有特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆