Rust module
Created By: chatGPT
In Rust, a module is a way to organize related functionality. Modules help in encapsulating items like functions, structs, traits, and so on. They can be declared using the
mod
keyword. Modules can be private or public, which controls the visibility of their contents. To declare a module, you can create a new file or write inline in your main file.// Declare a module named 'my_module'
mod my_module {
pub fn public_function() {
println!("This is a public function!");
}
fn private_function() {
println!("This is a private function!");
}
}
To use the module in your main program, you need to reference it. If the module is in a separate file, Rust requires the file to be named
my_module.rs
and located in the same directory as the main file. If the module is defined inline, you can use it immediately.fn main() {
// Call the public function from my_module
my_module::public_function();
// This will result in an error, as private_function is not accessible
// my_module::private_function();
}
Organizing modules in a hierarchy is possible. To create a nested module, simply declare a module within another. This aids in better organization of complex applications.
mod outer_module {
pub mod inner_module {
pub fn inner_function() {
println!("This is an inner function!");
}
}
}
fn main() {
outer_module::inner_module::inner_function();
}
Functions and other items defined inside a module can be made public or kept private by using the
pub
keyword. If an item is private, it can only be accessed within the same module. This feature of Rust promotes encapsulation and helps in maintaining a clean API.mod library {
pub struct Book {
title: String,
}
impl Book {
pub fn new(title: &str) -> Book {
Book {
title: title.to_string(),
}
}
fn read(&self) {
println!("Reading: {}", self.title);
}
}
}
fn main() {
let book = library::Book::new("The Great Gatsby");
// book.read(); // This line would cause an error because read is private
}
Using external crates can be facilitated via modules. By declaring an external dependency in your
Cargo.toml
, you can use the functionality within your modules. Make sure to keep your modules organized for better maintainability.[dependencies]
your_crate_name = "version"