从模块访问外部包装箱

问题描述 投票:2回答:1

我将依赖项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)
   |                  ^^^^

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

rust
1个回答
4
投票

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());
}

Playground

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

Foo { bar: thread_rng().gen_bool(0.5) }

Playground

© www.soinside.com 2019 - 2024. All rights reserved.