从模块访问外部包装箱

Wiz*_*zix 2 rust

我在rand项目中添加了依赖项:

[dependencies]
rand = "0.5"
Run Code Online (Sandbox Code Playgroud)

在我的中main.rs,我具有以下内容:

extern crate rand;

pub mod foo;
use foo::Foo;

fn main() {
    println!("{:#?}", Foo::new());
}
Run Code Online (Sandbox Code Playgroud)

并在文件中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) }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,出现以下错误:

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

如何使用模块中的外部包装箱?

ozk*_*iff 5

extern crateitem将板条箱的名称带入名称空间。该模块具有自己的名称空间,因此您需要导入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());
}
Run Code Online (Sandbox Code Playgroud)

操场

或者您可以导入use rand::{thread_rng, Rng};并将呼叫更改为

Foo { bar: thread_rng().gen_bool(0.5) }
Run Code Online (Sandbox Code Playgroud)

操场