Understanding Rust Module Visibility for Better Code Organization
Rust Module Visibility
Rust's module system provides a robust framework for organizing code and controlling access to various items within it. This document elucidates the concept of visibility in Rust, which dictates how items can be accessed from different parts of the code.
Key Concepts
- Modules: Containers for items (functions, structs, enums, etc.) that help keep the code organized.
- Visibility: Governs whether an item can be accessed externally or remains hidden within its module.
Visibility Levels
Rust offers three primary levels of visibility:
Module-level (pub(super)
)
Items can be accessed from the parent module.
mod parent_module {
mod child_module {
pub(super) fn super_function() {
println!("This function is accessible in the parent module.");
}
}
}
Crate-level (pub(crate)
)
Items are accessible from anywhere within the same crate but not from outside it.
mod my_module {
pub(crate) fn crate_function() {
println!("This function is accessible within the crate.");
}
}
Public (pub
)
Items can be accessed from other modules or crates. To make an item public, simply use the pub
keyword.
mod my_module {
pub fn public_function() {
println!("This is a public function.");
}
}
Private (default)
Items are restricted to the module in which they are defined and cannot be accessed externally.
mod my_module {
fn private_function() {
println!("This is a private function.");
}
}
Nesting Modules
Visibility rules extend to nested modules. Items within a module can be designated as public or private, influencing their accessibility from external sources or their nested modules:
- A public item in a parent module can be accessed by child modules.
- A private item in a child module is not accessible by the parent module.
Conclusion
Grasping the concept of visibility in Rust is essential for crafting well-structured code. By employing the right visibility modifier (private
, pub
, pub(crate)
, pub(super)
), you can effectively control how you expose your items to other parts of your codebase, facilitating encapsulation and promoting a clean architecture.