看看这个超级简单的婴儿围栏
fn main() {
for i in 0..10 {
println!("{}", i*0.5);
}
}
Run Code Online (Sandbox Code Playgroud)
在 Rust 1.0-beta.2 上编译的结果是“error: the trait core::ops::Mul<_>
is not implementation for the type _
”
我认为我需要以i
某种方式指定类型,但我正在努力寻找有关如何执行此操作的文档。
当整型变量不受其他约束时,它将回退到i32
。问题是您同时拥有不受约束的整数和浮点数,因此不清楚如何将它们相乘(因此出现错误)。由于无论如何你都必须将它们转换为相乘,所以我只需在 print 语句中转换循环变量:
fn main() {
for i in 0..10 {
println!("{}", (i as f64) * 0.5);
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道是否可以实际指定循环变量的类型。在这种情况下,我只是确保明确定义了范围:
fn main() {
for i in 0..10_u16 {
println!("{}", i * 0.5);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这仍然有相同的错误(但有更多细节):
<anon>:3:24: 3:31 error: the trait `core::ops::Mul<_>` is not implemented for the type `u16` [E0277]
<anon>:3 println!("{}", i * 0.5);
^~~~~~~
Run Code Online (Sandbox Code Playgroud)
正如我之前提到的,您不能隐式地将整数和浮点数相乘。你必须决定你想要它的含义。