Modules
01. In same file
Related code and data are grouped into a module and stored in the same file.
fn main() {
greetings::hello();
}
mod greetings {
// ⭐️ By default, everything inside a module is private
pub fn hello() { // ⭐️ So function has to be public to access from outside
println!("Hello, world!");
}
}Modules can also be nested.
fn main() {
phrases::greetings::hello();
}
mod phrases {
pub mod greetings {
pub fn hello() {
println!("Hello, world!");
}
}
}Private functions can be called from the same module or from a child module.
💡
selfkeyword is used to refer same module, whilesuperkeyword is used to refer parent module. Alsosuperkeyword can be used to access root functions from inside a module.
🔎 When writing tests it’s a good practice to write tests inside a test module because of they compile only when running tests.
02. In different file, same directory
If we wrap file content with a mod declaration, it will act as a nested module.
03. In different file, different directory
mod.rs in the directory module root is the entry point to the directory module. All other files in that directory root, act as sub-modules of the directory module.
Again, If we wrap file content with a mod declaration, it will act as a nested module.
Other files in the directory module act as sub-modules for mod.rs.
⭐️ If you need to access an element of phrases/greetings.rs from outside the module, you have to import greetings module as a public module.
🔎 It’s unable to import child file modules of directory modules to
main.rs, so you can’t usemod phrases::greetings;frommain.rs. But there is a way to importphrases::greetings::hello()tophrasesmodule by re-exportinghellotophrasesmodule. So you can call it directly asphrases::hello().
This allows you to present an external interface that may not directly map to your internal code organization. If still it is not clear, don’t worry; We discuss the usages of use on an upcoming section in this post.
Last updated