rust - Rust 的数据类型(例如 float)在哪里定义?

标签 rust

Rust 显然是一种新语言 (0.8)。它看起来很有趣,我开始研究它。我遇到了一些软件,其中 float 被更改为 f64,所以我想找到数据类型(包括 float)在哪里定义。我找不到任何非常具体的东西。我确实找到了:

There are three floating-point types: float, f32, and f64. Floating-point numbers are written 0.0, 1e6, or 2.1e-4. Like integers, floating-point literals are inferred to the correct type. Suffixes f, f32, and f64.

我猜“float”或“f”是 16 位。

更笼统地说(我不是计算机科学家),是否真的值得摆弄所有这些小数据类型,如 intint32int64ff32f64(仅举几例)。我能理解一些语言,例如。一个字节类型,因为字符串是一个相当复杂的类型。对于数字类型,我认为它只会造成不必要的复杂性。为什么不直接使用 i64f64 并将它们称为 intfloat(或 i64f64 以适应 future 的变化,或者默认使用 float 和 int)。

也许有一些低级程序需要较小的值,但为什么不将使用保留给那些需要它们的程序,而将它们放在核心之外呢?我发现从例如转换为不必要的苦差事。 inti64等,它到底实现了什么?或者,将它们留在“核心”中,但默认为 64 位类型。 64 位类型显然是必需的,而其余仅在特定情况下才需要 (IMO)。

最佳答案

floatf32f64 在 Rust 手册中定义:http://static.rust-lang.org/doc/0.8/rust.html#primitive-types

具体来说,对于float:

The Rust type float is a machine-specific type equal to one of the supported Rust floating-point machine types (f32 or f64). It is the largest floating-point type that is directly supported by hardware on the target machine, or if the target machine has no floating-point hardware support, the largest floating-point type supported by the software floating-point library used to support the other floating-point machine types.

因此 float 不是 16 位,它是 f32f64 的别名,具体取决于硬件。

要回答你问题的第二部分,在像 Rust 这样的低级语言中,不能简单地假设一个 float 是 64 位的,因为如果硬件本身不支持这种 float ,那么就有一个显着的性能损失。既不能有具有未指定表示的单个浮点类型,因为对于许多用例,需要保证操作数字的精度。

一般情况下,您会使用float,当您有特定需求时,您会使用f32f64

编辑 float 现在是removed from the language , 现在只有 f32f64 浮点类型。重点是所有当前架构现在都支持 64 位 float ,所以 float 始终是 f64,并且没有找到特定于机器的类型的用例。

关于rust - Rust 的数据类型(例如 float)在哪里定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416437/

相关文章:

enums - 我如何只匹配枚举的部分而不是所有变体?

Rust 所有权智能指针

types - 具有泛型类型的多个特征的类型别名

rust - 当外部生命周期不同时,为什么我不能将一个引用的引用取消引用分配给另一个引用?

pointers - 原始指针没有产生预期的效果

rust - 解释 *Rc::make_mut 的行为以及它与 Mutex 相比的不同之处

arrays - 如何将 GenericArray<T, ?> 转换为相同长度的数组?

postgresql - 如何使用 postgres crate 将表名作为变量传递给 execute()?

macros - 单个 Rust 宏可以生成多个声明吗?

rust - 我们可以自动导出用户定义的特征吗?