将大于 i32 的数字存储到变量中时,为什么不会出现文字超出范围错误?

Why do I not get a literal out of range error when storing a number larger than an i32 into a variable?

Rust 文档说默认整数类型是 i32,这意味着默认情况下变量可以保存的最大数字是 21474836472e31 - 1 。事实证明也是如此:如果我尝试在 x 变量中保存大于 2e31 - 1 的数字,我会得到错误 literal out of range

代码

fn main() {
    let x = 2147483647;
    println!("Maximum signed integer: {}", x);
    let x = 2e100;
    println!("x evalues to: {}", x);
}

但是如果我将值 2e100 保存在 x 变量中,为什么我不会收到错误消息?它的计算结果肯定大于 2e31 - 1.

输出

Maximum signed integer: 2147483647
x evalues to: 20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

代码

fn main() {
    let x = 2147483648;
    println!("Maximum signed integer: {}", x);
}

输出

error: literal out of range for i32
 --> src/main.rs:2:11
  |
2 |     let x=2147483648;
  |           ^^^^^^^^^^
  |
  = note: #[deny(overflowing_literals)] on by default

诸如2e100之类的常量文字不是整数文字而是浮点文字。这可以用

显示
fn main() {
    let () = 2e100;
}

产生

error[E0308]: mismatched types
 --> src/main.rs:2:9
  |
2 |     let () = 2e100;
  |         ^^ expected floating-point number, found ()
  |
  = note: expected type `{float}`
             found type `()`

另请参阅:

  • How do I print the type of a variable in Rust?