Rust,rand gen_range 需要 1 个参数,而不是 2 个?

Dre*_*rew 4 rust

我正在学习 rust lang 网站上的学习 rust 书,但随机数生成不起作用。

具体来说,当尝试像这样创建随机范围时:

use rand::Rng;

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

我收到错误:

    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.
Run Code Online (Sandbox Code Playgroud)

Rust 操场上,我遇到了同样的错误?

本地和操场上的 rand 版本都是0.8.0.

Apl*_*123 9

解决此类错误的最简单方法是在文档中搜索gen_rangecrate (rand)。你会发现它是trait的一个方法Rng,它只有一个参数:范围。因此,为它提供一个范围:

rand::thread_rng().gen_range(1..101)
Run Code Online (Sandbox Code Playgroud)