Modules, paths, and imports
Rust provides us with a lot of flexibility in terms of how we organize our project, as we saw in Chapter 2, Managing Projects with Cargo. Here, we'll go into some of the advanced aspects of modules and different ways to introduce more privacy in our code.
Imports
We can do nested imports of items from modules. This helps in reducing the taken up by imports. Consider the following code:
// nested_imports.rs use std::sync::{Mutex, Arc, mpsc::channel}; fn main() { let (tx, rx) = channel(); }
Re-exports
Re-exports allows one to selectively expose items from a module. We were already using the convenience of reexports when we used the Option
and Result
types. Re-exports also helps in reducing the import path one has to write if the module is created a nested directory containing many submodules.
For example, here we have a sub module named bar.rs
from a cargo project we created called reexports
:
// reexports_demo/src/foo/bar.rs pub struct Bar;
The Bar
is a publicly...