Reputation: 1738
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)
}
this code compiled before Rust beta, but now it doesn't:
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)
^~~~~~~~~~~~
I must write this code to compile:
extern crate rand;
fn test(a: isize) {
println!("{}", a);
}
fn main() {
test(rand::random::<isize>() % 20)
}
How can I make the compiler infer the type?
Upvotes: 1
Views: 143
Reputation: 15012
The compiler cannot infer the type in this situation, there are too many unknowns.
Let us call R
the output type of rand::random()
, and I
the type of 20
.
The conditions imposed by test(rand::random() % 20)
are only:
R: Rand + Rem<I, Ouput=isize>
I: integral variable (i8, u8, i16, u16, i32, u32, i64, u64, isize or usize)
Nothing guaranties that only a single pair (T, I)
will meet these requirements (and it's actually quite easy to create a new type T
fulfilling them), thus the compiler cannot choose by itself.
Thus using rand::random::<isize>()
is the correct approach here.
Upvotes: 5