by lucaotta · 9y ago · 0 comments
I'm writing an application. Inside main.rs I can write
extern crate foo;
use foo::Bar;
If I create a module and use the same crate, I need to write: extern crate foo;
use self::foo::Bar;
This always surprises me and I never found anything explicit written on the Book. To me, it looks like a nice papercut to fix.One thing that might be confusing is that `main.rs` is the entry file of binary crates, while `lib.rs` is the entry file of library crates, and a project can contain both a binary and a library crate. The binary crate then does need to `extern crate` the library crate.
We've been working on a new version of the book, if you have time, I'd love if you would take a look at the new chapter on modules [1] and file PRs or issues on the repo [2] if it's still confusing or leaving you with unresolved questions!
[1] - http://rust-lang.github.io/book/ch07-00-modules.html [2] - https://github.com/rust-lang/book
My typical use case is importing definitions, for example an error type or enum from the crate, let's say something from tokio_core.
I'd like to use this enum both in main and in my module; from my (limited) experience, you need to extern crate tokio_core both in main and the module, then use the definition. In this case the syntax is different for somewhat obscure reasons.
I made a simple example with just two files: (In the meanwhile I realized that my first example was wrong :) https://github.com/lucaotta/rust_modules
Let's say that after my refactor, I've "moved" the crate import into the module since "logically" it belongs there. In this case the compilation fails if I don't use self::. But previously it was working in main.rs! And I have no idea why...