Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 349
Ismail Shah Avatar asked Dec 14 '22 07:12

Ismail Shah


1 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.

like image 80
pretzelhammer Avatar answered Jan 01 '23 05:01

pretzelhammer