欢迎来到 Stack Overflow。以后,请尝试在您的问题中添加更多信息,包括相关链接(您在说哪个文档)、源代码和错误消息。这将使我们更容易提供相关且有用的答案。
我假设你正在做这样的事情:
use rand::thread_rng;
fn main() {
let x = thread_rng().gen_range(0, 10);
println!("{}", x);
}
Playground
这给出了以下错误:
error[E0599]: no method named `gen_range` found for struct `rand::rngs::thread::ThreadRng` in the current scope
--> src/main.rs:4:26
|
4 | let x = thread_rng().gen_range(0, 10);
| ^^^^^^^^^ method not found in `rand::rngs::thread::ThreadRng`
|
::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/rand-0.7.3/src/lib.rs:212:8
|
212 | fn gen_range<T: SampleUniform, B1, B2>(&mut self, low: B1, high: B2) -> T
| ---------
| |
| the method is available for `std::boxed::Box<rand::rngs::thread::ThreadRng>` here
| the method is available for `std::sync::Arc<rand::rngs::thread::ThreadRng>` here
| the method is available for `std::rc::Rc<rand::rngs::thread::ThreadRng>` here
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use rand::Rng;
|
请注意,Rust 编译器非常擅长为修复代码的方法提供建议。在这种情况下,错误的最后一行建议添加use rand::Rng;,现在它可以工作了:
use rand::Rng;
use rand::thread_rng;
fn main() {
let x = thread_rng().gen_range(0, 10);
println!("{}", x);
}
Playground
这是因为gen_range 方法没有直接在ThreadRng 结构上实现,而是在通用Rng 特征中实现,这使得它自动可用于所有随机数生成器。然而,trait 中的方法只有在 trait 本身可用时才可用,因此需要先导入 rand::Rng。