Why can't I call gen_range with two i32 arguments?

Viewed 1111

I have this code but it doesn't compile:

use rand::Rng;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(0, 101);
    println!("The secret number is: {}", secret_number);

    println!("Please input your guess.");
    let mut guess = String::new();
    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");
    println!("You guessed: {}", guess);
}

Compile error:

error[E0061]: this function takes 1 argument but 2 arguments were supplied
 --> src/main.rs:7:44
  |
7 |     let secret_number = rand::thread_rng().gen_range(0, 101);
  |                                            ^^^^^^^^^ -  --- supplied 2 arguments
  |                                            |
  |                                            expected 1 argument
2 Answers

The gen_range method expects a single Range argument, not two i32 arguments, so change:

let secret_number = rand::thread_rng().gen_range(0, 101);

to:

let secret_number = rand::thread_rng().gen_range(0..101);

And it will compile and work. Note: the method signature was updated in version 0.8.0 of the rand crate, in all prior versions of the crate your code should work as-is.

run cargo update It will list the version for rand.

update the version in Cargo.toml under dependencies

[dependencies] rand = "0.8.3"

hopefully this solves the above problem

Related