rustc 1.0.0-每晚(be9bd7c93 2015-04-05)(2015-04-05建成)
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random() % 20)
}
这段代码是在Rust测试版之前编译的,但现在没有了:
src/main.rs:8:10: 8:22 error: unable to infer enough type information about `_`; type annotations required [E0282]
src/main.rs:8 test(rand::random() % 20)
^~~~~~~~~~~~
我必须编写以下代码才能编译:
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random::<isize>() % 20)
}
如何使编译器推断类型?
在这种情况下,编译器无法推断类型,因为未知项太多。
让我们把R
称为rand::random()
的输出类型,把I
称为20
的类型。
test(rand::random() % 20)
施加的条件仅为:
R: Rand + Rem<I, Ouput=isize>
I: integral variable (i8, u8, i16, u16, i32, u32, i64, u64, isize or usize)
没有什么能保证只有一对(T, I)
能够满足这些要求(实际上,创建一个满足这些要求的新类型T
非常容易),因此编译器无法自行选择。
因此,使用rand::random::<isize>()
是正确的方法。