2

I added the dependency rand to my project:

[dependencies]
rand = "0.5"

In my main.rs, I have the following:

extern crate rand;

pub mod foo;
use foo::Foo;

fn main() {
    println!("{:#?}", Foo::new());
}

And in the file 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) }
    }
}

And when I try to compile it, I have the following error:

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)
   |                  ^^^^

How can I use external crates from modules?

1 Answer 1

5

extern crate item brings crate's name into the namespace. The module has its own namespace so you need to import rand itself - use rand::{self, Rng}; - because you're calling 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

Or you can import use rand::{thread_rng, Rng}; and change the call to

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

Playground

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.