Rust Modules
Organizing and structuring your Rust code
📦 What are Rust Modules?
Modules in Rust help organize code into logical groups, control visibility, and create namespaces. They're like folders for your functions, structs, and other items, making large projects manageable and clean.
// Simple module example
mod greetings {
pub fn hello() {
println!("Hello from module!");
}
}
fn main() {
greetings::hello();
}
Types of Modules
Inline Modules
Defined directly in the same file
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
File Modules
Separate files for organization
// In main.rs
mod utils;
// In utils.rs
pub fn helper() {
println!("Helper function");
}
Directory Modules
Folders with mod.rs files
// src/network/mod.rs
pub mod client;
pub mod server;
// src/network/client.rs
pub fn connect() { }
Private/Public
Control access with pub keyword
mod secret {
fn private() { }
pub fn public() { }
}
🔹 Basic Module Example
Here's how to create and use a simple module:
// Define a module
mod calculator {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
pub fn multiply(x: i32, y: i32) -> i32 {
x * y
}
// Private function (not accessible outside)
fn internal_helper() {
println!("This is private");
}
}
fn main() {
let sum = calculator::add(5, 3);
let product = calculator::multiply(4, 6);
println!("Sum: {}", sum); // Output: Sum: 8
println!("Product: {}", product); // Output: Product: 24
}
Output:
Sum: 8
Product: 24
🔹 File-based Modules
Organize code across multiple files:
🔸 main.rs
mod shapes; // This looks for shapes.rs
fn main() {
let area = shapes::rectangle::area(10, 5);
println!("Rectangle area: {}", area);
}
🔸 shapes.rs
pub mod rectangle {
pub fn area(width: u32, height: u32) -> u32 {
width * height
}
pub fn perimeter(width: u32, height: u32) -> u32 {
2 * (width + height)
}
}
pub mod circle {
pub fn area(radius: f64) -> f64 {
3.14159 * radius * radius
}
}
🔹 Using 'use' for Imports
Simplify module access with the 'use' keyword:
mod math {
pub mod operations {
pub fn add(a: i32, b: i32) -> i32 { a + b }
pub fn subtract(a: i32, b: i32) -> i32 { a - b }
}
}
// Import specific functions
use math::operations::add;
use math::operations::subtract;
// Or import the whole module
use math::operations;
fn main() {
// Direct usage after import
println!("5 + 3 = {}", add(5, 3));
// Module usage
println!("10 - 4 = {}", operations::subtract(10, 4));
}