1
votes

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?

1
also note that you should not be using random() and then % 20 to get a number between 0 and 20, but a rand::distributions::Range (see example doc.rust-lang.org/rand/rand/… ). The issue with using the modulo operator is, that you don't get a truly random distribution. You are instead increasing the probability for small numbers.oli_obk

1 Answers

5
votes

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.