默认浮点类型是什么?

Hol*_*ger 8 floating-point rust

如果变量指定为浮点类型a,则abs可以使用该函数。以下示例正在运行:

fn main() {
    let a = -1.0f64;
    println!("{:?}", a.abs());
}
Run Code Online (Sandbox Code Playgroud)

1它按预期打印。但如果f64省略,则会在编译期间引发错误,如下例所示:

fn main() {
    let a = -1.0;
    println!("{:?}", a.abs());
}
Run Code Online (Sandbox Code Playgroud)

该版本出现以下故障:

   Compiling playground v0.1.0 (file:///C:/git/Rust/playground)
src\main.rs:3:24: 3:29 error: no method named `abs` found for type `_` in the current scope
src\main.rs:3     println!("{:?}", a.abs());
                                     ^~~~~
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
src\main.rs:3:5: 3:31 note: expansion site
src\main.rs:3:24: 3:29 help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
src\main.rs:3:24: 3:29 help: candidate #1: use `core::num::Float`
error: aborting due to previous error
Could not compile `playground`.

To learn more, run the command again with --verbose.
Run Code Online (Sandbox Code Playgroud)

该消息表示 的类型a_。我猜这个abs函数不能用,因为不清楚,具体类型a是什么。这是否意味着编译时未定义类型?如果 Rust 中没有声明特定的浮点类型,则使用什么类型?

She*_*ter 7

RFC 212说:

类型不受约束的整数文字将默认为i32[...] 浮点文字将默认为f64.

然而,在大多数情况下,某些东西会将推断类型限制为具体类型,例如将其传递给方法或将其放入结构中。

这是否意味着编译时未定义类型?

类型始终在代码实际编写之前定义。然而,整数或浮点文字的具体类型徘徊在类型的量子叠加中,直到有某种东西迫使它以这种或另一种方式存在。如果没有什么强制它,那么它会恢复到默认值。

这就是最终允许这样的代码工作的原因:

use std::{f32, f64};

fn main() {
    let a = -1.0;
    let b = -1.0;

    println!("{:?}", f32::abs(a));
    println!("{:?}", f64::abs(b));
}
Run Code Online (Sandbox Code Playgroud)

可以预期,如果变量是 af32或 an f64,则继续选择一个。我不知道编译器内部是否能够具体回答,但似乎默认类型后备发挥作用太晚了,无法保存您的代码。当方法查找发生时,它想知道变量的类型以找到有效的匹配,但它还不可用。

  • 为什么OP的代码不能编译呢?([此处](https://play.rust-lang.org/?gist=10e4887dbc2efe616cd1&amp;version=stable)) (2认同)
  • @Shepmaster:好吧,如果没有规范,很难说,但如果编译器没有足够早地执行回退,这对我来说听起来像是一个错误...... (2认同)