Hi, I have a style question -- do you think it is better to declare extern crate foo
in every module that uses foo, or only once per crate? The first option has the advantage of making the modules more self contained, the other option has a little less noise on top of the source file. Are there any best practices related to this?
It's usually recommended to do it in the crate root, because of how name spaces works.
extern crate lib;
mod foo {
use lib::bar;
}
v.s.
mod foo {
extern crate lib;
use self::lib::bar; //or use foo::lib::bar;
}
The latter may cause some confusion, and duplications of lib
when it's used in multiple modules. Especially since (I assume) most people are used to only having extern crate
in the crate root.
Help me with minor question please. I have src/main.rs
where I have put extern crate lib;
but in modules (like src/mytest.rs
) I can't use lib::function()
as you say until I add use lib;
in the src/mytest.rs
file. Is everything correct?
Actually yes. Paths in expressions, like function calls, are always local to the module, which is why you have to import lib
with use, but paths in use
statements are always global, which is why you can reach lib
there. You can begin a path with ::
to make it global, so ::lib::function()
should work.
Edit: Some formatting.
This chapter of the Rust Book might be an interesting read or you:
http://rust-lang.github.io/book/second-edition/ch07-03-importing-names-with-use.html