Rust Modules
Written
- Source: https://doc.rust-lang.org/rust-by-example/mod.html
- Each file and directory is a module by default.
- In a directory,
mod.rsis the "main" file for the module and the other files are nested modules under that module. Other files must be referenced withmod FILENAMEto be included. - You can also define nested modules within the same file.
- Visibility
- Items in modules are private by default
pubmakes them visible outside the module.- Nested modules within a file can be declared with
pub modto make them public. pub(in path)lets you define specific paths where the item should be importable.- e.g.
pub(in crate::other_module)
- e.g.
pub(self)is public only within the current module, which is effectively the same as the default private visibility.pub(super)makes it visible to the parent module.pub(crate)makes it visible within the whole crate.- Notably, access to any item msut be allowed to the importer along the whole chain. Declaring a function
pubin a module that isn't visible outside the crate doesn't actually expose that field to external importers. The module itself must be exposed in some way too. - In structures, fields and functions are also private by default even if the structure itself is public. All the
pubmodifiers above apply when you do want to expose them.
usesyntax- You can access anything visible with the entire full path to the item, but
usemakes it simpler. use crate::a::b::{ fn1, fn2 }will exposefn1andfn2in the module's scope.use X as Ywill rename the function too.pub usereexports an imported module or other item.
- You can access anything visible with the entire full path to the item, but
super::other_module::Xandself::Xcan help for relative references and to remove ambiguity.