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

标签 rust

这个问题在这里已经有了答案:





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

(2 个回答)


10 个月前关闭。




我正在学习 rust lang 网站上的学习 rust 书,但随机数生成不起作用。
具体来说,当尝试像这样创建随机范围时:

use rand::Rng;

fn main() {
    let s: u32 = rand::thread_rng().gen_range(1, 101);
    println!("{}", s);
}
我收到错误:
    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.
rust playground我犯了同样的错误?
本地和操场上的 rand 版本是 0.8.0 .

最佳答案

解决此类错误的最简单方法是 search for gen_range in the docs for the crate (rand) .你会发现它是一个 method of the Rng trait ,它需要一个参数:范围。因此,为它提供一个范围:

rand::thread_rng().gen_range(1..101)

关于Rust,rand gen_range 需要 1 个参数,而不是 2 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65431949/

相关文章:

types - 为数字提供显式类型

rust - 如何将 hashbrown 数据类型与 Rayon 并行迭代器一起使用?

rust - 移动结构时如何自动清除结构中的属性?

rust - 我认为我没有借用的变量的生命周期错误

java - Rust和Java Ghidra进程访问权限之间的命名管道

rust - 是否可以将 `Borrow<T>` 转换为 `AsRef<T>` 或反之亦然?

multithreading - 在新线程(Rust)中从共享库执行异步函数

reference - 迭代器通过引用返回项目,生命周期问题

rust - 我什么时候应该在 Rust 中使用特征作为类型?

function - 在 Rust 中实际需要 move 到函数的情况