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

白昼怎懂夜的黑 提交于 2020-12-27 07:14:09

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/65431713/why-cant-i-call-gen-range-with-two-i32-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!