Skip to content

Instantly share code, notes, and snippets.

@mitchmindtree
Created May 29, 2014 15:56
Show Gist options
  • Save mitchmindtree/357fafc1c9fa5db3b10d to your computer and use it in GitHub Desktop.
Save mitchmindtree/357fafc1c9fa5db3b10d to your computer and use it in GitHub Desktop.
A question about Rust 'mod', 'crate' and 'use' usage.
//--------------- main.rs ---------------------
extern crate rand; // Why do I have to use this here, when I've already done so in a.rs?
mod a;
mod b;
fn main() {
a::test();
b::test();
}
//-------------- a.rs ---------------------
extern crate rand;
use rand::{random, task_rng, Rng}
use b;
pub fn test() {
// Stuff where random, task_rng, Rng and b are used and printed...
}
//-------------- b.rs ---------------------
extern crate std;
use std::vec;
pub fn test() {
// Stuff where vec is used and printed...
}
/*
My Question:
Why is it that when I remove "extern crate rand;" from line 3 in main.rs
rustc fails to recognise "random, task_rng and Rng" when used in a.rs? I
ask this because rustc seems to recognise my usage of std::vec in b.rs
totally fine, despite only having used "extern crate std;" in b.rs and
not in main.rs like I have to for "extern crate rand;"
NOTE: all files are in the same directory.
*/
@mitchmindtree
Copy link
Author

The solution was:

  1. all extern crates should be imported in the crate root - NOTE: the crate root is where 'fn main' is.
  2. extern crate std is implicitly imported to the crate root by the compiler, thus it was unnecessary for me to implement it anyway.
    extern crate std is

I ended up removing 'extern crate rand' from a.rs and 'extern crate std' from b.rs and everything works as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment