取随机数的模数时类型推断失败
Type inference failure when taking the modulus of a random number
rustc 1.0.0-nightly (be9bd7c93 2015-04-05) (built 2015-04-05)
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random() % 20)
}
此代码在 Rust beta 之前编译,但现在没有:
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>()
是正确的方法。
rustc 1.0.0-nightly (be9bd7c93 2015-04-05) (built 2015-04-05)
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random() % 20)
}
此代码在 Rust beta 之前编译,但现在没有:
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>()
是正确的方法。