为什么不能比较两个不同类型的整数? [英] Why can't I compare two integers of different types?

查看:76
本文介绍了为什么不能比较两个不同类型的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let x: i32 = 4;
let y: i16 = 4;

println!("{}", x == y);

在编译上面的代码片段时,编译器输出以下错误:

When compiling the snippet above, the compiler prints the following error:

error[E0308]: mismatched types
 --> src/main.rs:5:25
  |
5 |     println!("{}", x == y);
  |                         ^ expected i32, found i16

似乎 PartialEq 。在 f32 f64 之间以及对于 PartialOrd 也一样有什么理由吗?

It seems that PartialEq is not implemented for different types of integers. The same happens between f32 and f64, and for PartialOrd as well. Is there a reason for that? Is it intended to be implemented in future versions of Rust?

推荐答案

Rust中有很多整数类型:

There are many integral types, in Rust:


  • i8 i16 i32 i64 i128

  • u8 u16 u32 u64 u128

  • isize

  • 使用

  • i8, i16, i32, i64 and i128,
  • u8, u16, u32, u64 and u128,
  • isize,
  • usize.

在某些情况下,混合算术或比较将具有明显的实现方式,因为可能在一个方向上进行无损转换:

In some cases, mixed arithmetic or comparisons would have an obvious implementation as a lossless conversion is possible in one direction:


  • <如果 x< code> i< x> 始终可以转换为 i< y> 。 y

  • u< x> 始终可以转换为 u< y> 如果 x< y

  • u< x> 始终可以转换为 i< y> 如果 x< y

  • i<x> can always be converted to i<y> if x < y,
  • u<x> can always be converted to u<y> if x < y,
  • u<x> can always be converted to i<y> if x < y.

但是,某些转化并不明显或无法移植:

Some conversions, however, are not obvious or not portable:


  • i< x> 不能转换为 u< y> 不管 x y 的值分别是什么,

  • isize usize 在任何位置都有特定于平台的大小,可小至16位,大至64位

  • i<x> cannot be converted to u<y> no matter what the respective values of x and y are,
  • isize and usize have a platform specific size anywhere, as small as 16 bits but as large as 64 bits.

因此,由于Rust不热衷于上溢或下溢,因此任意混合算术不太可能否则将实现比较。

Therefore, since Rust is not keen on overflows or underflows, it is unlikely that arbitrary mixed arithmetic or comparisons will ever be implemented.

可以实现一个受限子集,但随后引发两个问题:

A restricted subset could be implemented, but then two questions are raised:


  • 不是不符合人体工程学的受限子集吗?

  • 不是使用混合类型表示设计问题吗?同样,数量应该具有单位,数量应该具有已知的幅度。

这篇关于为什么不能比较两个不同类型的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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