为什么不能比较两个不同类型的整数? [英] Why can't I compare two integers of different types?
问题描述
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 $ c $没有为不同类型的整数实现c>。在
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
andi128
,u8
,u16
,u32
,u64
andu128
,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 toi<y>
ifx < y
,u<x>
can always be converted tou<y>
ifx < y
,u<x>
can always be converted toi<y>
ifx < 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 tou<y>
no matter what the respective values ofx
andy
are,isize
andusize
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屋!