Unlike other programming languages, a module do not represent a file. It represents something more. It is very similar to a "package" or a "namespace". One Rust source file *.rs can contain one or more modules.
Each module can contain other modules inside. This will create a hierarchy. You can use two columns "::" as delimiter to identify a module component similar to URL that is using "/" as delimiter.
Example: module::sub-module::component-name
You can use "pub" keyword to define public modules. This indicate that a module member can be used outside of module scope. You can use "*" to import all "pub" members defined into a module or you can specify each member to be imported by name. After import you can use the members as part of current scope.
In this example modules are defined in a single file:
pub mod first_module {
pub mod sub_module {
pub fn test() {
println!("You found me again");
}
} //end sub_module
pub fn test() {
println!("You found me");
}
} // end first_module
// import in current namespace all elements of first_module
use first_module::*;
fn main() {
test(); // You found me
sub_module::test(); // You found me again
}
Notes:
Homework: This example can be tested live: modules
Read next: Errors