Rust Modules & Crates Tutorial | Organize Your Rust Code with mod, pub, use | Rust for Beginners #29
Video: Rust Modules & Crates Tutorial | Organize Your Rust Code with mod, pub, use | Rust for Beginners #29 by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Modules & Crates Tutorial: Organize Your Rust Code with mod, pub, and use
Rust modules help you organize code into logical units, control visibility, and keep your projects maintainable as they grow. This guide covers declaring modules with mod, making items public with pub, importing with use, aliasing imports, and using standard library collections like HashMap and HashSet.
Code
// Declare a module named greetings
mod greetings {
// Make this function public so it can be called from outside the module
pub fn hello() {
println!("Hello from the greetings module!");
}
}
// Nested modules example
mod shapes {
pub mod circle {
pub fn area(radius: f64) -> f64 {
3.14159 * radius * radius
}
}
pub mod rectangle {
pub fn area(width: f64, height: f64) -> f64 {
width * height
}
}
}
// Import functions directly to avoid typing full paths
use greetings::hello;
use shapes::circle::area as circle_area;
use shapes::rectangle::area as rect_area;
// Using standard library collections
use std::collections::{HashMap, HashSet};
fn main() {
// Call the public function from greetings module
hello();
// Calculate areas using nested modules
println!("Circle area: {}", circle_area(2.0));
println!("Rectangle area: {}", rect_area(3.0, 4.0));
// Create and use a HashMap
let mut scores = HashMap::new();
scores.insert("Alice", 50);
scores.insert("Bob", 60);
// Iterate over key-value pairs
for (name, score) in &scores {
println!("{}: {}", name, score);
}
// Lookup a value safely
if let Some(score) = scores.get("Alice") {
println!("Alice's score is {}", score);
}
// Create and use a HashSet
let mut fruits = HashSet::new();
fruits.insert("apple");
fruits.insert("banana");
fruits.insert("apple"); // duplicate ignored
println!("Fruits set contains apple? {}", fruits.contains("apple"));
println!("Fruits set contains orange? {}", fruits.contains("orange"));
}
Key Points
- Use
modto declare modules and group related code together. - Add
pubto functions or items to make them accessible outside their module. - Nested modules help organize code hierarchically and can have their own visibility rules.
- The
usekeyword imports items into scope, simplifying access and allowing aliasing withas. - Rust’s standard library collections like
HashMapandHashSetprovide powerful data structures for common tasks.