Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust, rand gen_range wants 1 arg, not 2? [duplicate]

Tags:

rust

I am following along the learn rust book from the rust lang website and random number generation is not working.

Specifically, when trying to create a random range like so:

use rand::Rng;

fn main() {
    let s: u32 = rand::thread_rng().gen_range(1, 101);
    println!("{}", s);
}

I get the error:

    Checking learn-rust v0.1.0 (.../learn-rust)
error[E0061]: this function takes 1 argument but 2 arguments were supplied
 --> src/main.rs:8:37
  |
8 |     let s: u32 = rand::thread_rng().gen_range(1, 101);
  |                                     ^^^^^^^^^ -  --- supplied 2 arguments
  |                                     |
  |                                     expected 1 argument

error: aborting due to previous error

For more information about this error, try `rustc --explain E0061`.
error: could not compile `learn-rust`

To learn more, run the command again with --verbose.

In the rust playground I get the same error?

The version of rand on both local and playground is 0.8.0.

like image 744
Drew Avatar asked Dec 23 '20 22:12

Drew


1 Answers

The easiest way to resolve an error like this is to search for gen_range in the docs for the crate (rand). You'll find that it's a method of the Rng trait, and it takes a single argument: the range. So, supply it with a range:

rand::thread_rng().gen_range(1..101)
like image 106
Aplet123 Avatar answered Sep 28 '22 08:09

Aplet123