为什么有符号整数的绝对值方法不返回无符号值? [英] Why don't the absolute value methods on signed integers return unsigned values?
问题描述
以下代码无法编译:
fn main() {
let x = (-5i32).abs();
let z: u32 = x;
}
带有消息:
error[E0308]: mismatched types
--> src/main.rs:4:18
|
4 | let z: u32 = x;
| ^ expected u32, found i32
阅读文档,看起来不错i32
的原因在于 i32::min_value()
在 i32
中没有正面表示.然而,它将在u32
中有一个正表示,它可以表示两倍大的数字.
Reading the documentation, it looks the choice of i32
stems from the fact that i32::min_value()
has no positive representation in i32
. However, it would have a positive representation in u32
, which can represent numbers twice as large.
我正在学习这门语言,并想了解为什么要做出某些设计决策,以便我可以养成良好的习惯.我觉得这个很混乱.有人可以解释为什么它以这种方式工作,而不是仅仅返回一个 u32
,这似乎是语义上正确的类型吗?
I'm learning the language, and want to understand why certain design decisions were made so that I can develop good habits. I find this one confusing. Can someone explain why it works this way instead of just returning a u32
, which would seem to be the semantically correct type?
推荐答案
有一个链接到 开发会议纪要,在 提议的 RFC更改 abs() 以返回无符号整数"
看起来主要原因是:
- 许多其他语言使用
i32
->i32
(例如C、Java),因为不小心将其他值提升为u32
可能会导致错误.出于这个原因,Rust 似乎最初使用了i32
->i32
(即遵循约定),但没有遇到相同类型的错误. - 直到 Rust 达到测试版后才提交此功能请求.开发人员不愿意对语言进行重大更改,因为它似乎是一个罕见的错误.这看起来是保持这种方式的主要原因.
- Many other languages use
i32
->i32
(for instance, C, Java), because the accidental promotion of other values tou32
might cause bugs. Rust seems to have usedi32
->i32
for this reason originally (i.e. following convention), but doesn't suffer from the same kinds of bugs. - This feature request wasn't submitted until after Rust had reached beta. The developers were not willing to introduce a breaking change to the language over what appears to be a rare bug. This looks like the main reason offered for keeping things this way.
似乎已接受的解决方法是使用 as u32
进行转换.
It seems like the accepted workaround is to use as u32
to cast.
i32::overflowing_abs
i32::wrapping_abs
和 i32::checked_abs
为 i32::min_value()
错误,但它们都不会产生 u32.
i32::overflowing_abs
i32::wrapping_abs
and i32::checked_abs
implement other solutions to the i32::min_value()
bug, but none of them produces a u32.
这篇关于为什么有符号整数的绝对值方法不返回无符号值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!