我将依赖项rand
添加到我的项目中:
[dependencies]
rand = "0.5"
在我的main.rs
中,我有以下内容:
extern crate rand;
pub mod foo;
use foo::Foo;
fn main() {
println!("{:#?}", Foo::new());
}
并在文件foo.rs
:
use rand::Rng;
#[derive(Debug)]
pub struct Foo { bar: bool }
impl Foo {
pub fn new() -> Foo {
Foo { bar: rand::thread_rng().gen_bool(0.5) }
}
}
当我尝试编译它时,我有以下错误:
error[E0658]: access to extern crates through prelude is experimental (see issue #44660)
--> src\foo.rs:11:18
|
11 | bar: rand::thread_rng().gen_bool(0.5)
| ^^^^
如何使用模块中的外部包装箱?
extern crate
项目将crate的名称带入命名空间。该模块有自己的命名空间,因此您需要导入rand
本身 - use rand::{self, Rng};
- 因为您正在调用rand::thread_rng()
:
extern crate rand;
mod foo {
use rand::{self, Rng};
#[derive(Debug)]
pub struct Foo { bar: bool }
impl Foo {
pub fn new() -> Foo {
Foo { bar: rand::thread_rng().gen_bool(0.5) }
}
}
}
use foo::Foo;
fn main() {
println!("{:#?}", Foo::new());
}
或者您可以导入use rand::{thread_rng, Rng};
并将呼叫更改为
Foo { bar: thread_rng().gen_bool(0.5) }