如果变量 a
指定为浮点型,可以使用 abs
函数。下面是运行的示例:
fn main() {
let a = -1.0f64;
println!("{:?}", a.abs());
}
它按预期打印1
。但如果省略f64
,则会在编译过程中抛出错误,如下例所示:
fn main() {
let a = -1.0;
println!("{:?}", a.abs());
}
这个版本报以下错误:
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.
这条信息表示a
的类型为_
。我猜测不能使用abs
函数,因为不清楚a
的具体类型是什么。这意味着在编译时没有定义类型吗?如果在Rust中没有声明特定的浮点类型,会使用哪种类型?
f64
,则在上述代码中应使用f64
的abs
函数。但是,由于错误消息中的_
未指定类型。 - Holger