Rust module system
Created By: chatGPT
The Rust module system provides a way to create namespaces that helps manage code organization and visibility. Modules in Rust can be defined using the
mod
keyword, allowing you to encapsulate functionality and create a clear structure for your programs. A module can contain functions, structs, enums, and other modules, which can all be accessed based on their visibility (public or private). Here’s a basic overview of how to define and use modules in Rust.mod my_module {
pub fn say_hello() {
println!("Hello from my module!");
}
}
fn main() {
my_module::say_hello();
}
Modules can also be nested. In the example below, we define a module inside another module. This allows more granular control over the structure of your code.
mod outer {
pub mod inner {
pub fn greet() {
println!("Greetings from the inner module!");
}
}
}
fn main() {
outer::inner::greet();
}
Sometimes you might want to create a submodule in a separate file. To do this, you place the definitions in their respective files and the Rust compiler will automatically link them. For example, if you have a directory structure like:
src/
main.rs
my_module/
mod.rs
submodule.rs
Your main file can declare the module as follows:
mod my_module;
fn main() {
my_module::some_function();
}
In the my_module/mod.rs
file, you would declare your submodule like this:
rust pub mod submodule;
pub fn some_function() { println!("Some function inside my_module!"); }
In the my_module/submodule.rs
file, you can define public functions as well:
pub fn display_message() {
println!("Hello from the submodule!");
}
Visibility is an important concept in the Rust module system. By default, all items (functions, structs, etc.) are private to the module they are declared in. Use the
pub
keyword to make items public and accessible from outside the module. Keeping items private helps encapsulate your module’s functionality and prevents accidental misuse.mod visibility_demo {
fn private_function() {
println!("This is private!");
}
pub fn public_function() {
println!("This is public!");
}
}
You can also bring items into scope using the
use
keyword, which helps simplify access to functions or structs across modules. Here’s how you can use it:mod activities {
pub fn run() {
println!("Running an activity!");
}
}
fn main() {
use activities::run;
run();
}