Rust's module system is a powerful feature that allows developers to organize and structure their code efficiently. It provides a way to encapsulate functionality, control visibility, and create reusable components.
Modules in Rust are containers for code that group related functionality together. They help in managing large codebases by breaking them into smaller, more manageable pieces. Modules can contain functions, structs, enums, traits, and even other modules.
To create a module in Rust, use the mod keyword followed by the module name. Here's a simple example:
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn subtract(a: i32, b: i32) -> i32 {
a - b
}
}
In this example, we've created a module named math with two functions: add and subtract.
pub KeywordBy default, items in Rust modules are private. To make them accessible from outside the module, use the pub keyword. In the previous example, add is public, while subtract is private.
To use items from a module, you can use the module name followed by the double colon :: operator:
fn main() {
let result = math::add(5, 3);
println!("5 + 3 = {}", result);
}
Modules can be nested within other modules, allowing for a hierarchical structure:
mod geometry {
pub mod shapes {
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
impl Rectangle {
pub fn area(&self) -> f64 {
self.width * self.height
}
}
}
}
use KeywordThe use keyword allows you to bring items from modules into scope, making them easier to access. This is particularly useful for frequently used items:
use geometry::shapes::Rectangle;
fn main() {
let rect = Rectangle { width: 5.0, height: 3.0 };
println!("Area: {}", rect.area());
}
use keyword to simplify access to frequently used itemsTo further enhance your understanding of Rust's module system, explore these related topics:
By mastering Rust's module system, you'll be able to create well-organized, maintainable, and scalable Rust projects. This foundational knowledge is crucial for building complex applications and libraries in Rust.