Modules help organize code into logical units with controlled visibility.
mod garden {
pub mod vegetables {
pub fn plant() {
println!("Planting vegetables!");
}
}
fn private_helper() {
// Only accessible within garden module
}
}| Keyword | Visibility |
|---|---|
| (none) | Private to current module |
pub | Public |
pub(crate) | Public within crate |
pub(super) | Public to parent module |
In Rust, everything is private by default! You must explicitly mark items as pub to make them accessible.
// Absolute path
crate::garden::vegetables::plant();
// Relative path
garden::vegetables::plant();
// With use statement
use garden::vegetables::plant;
plant();Access parent module:
mod parent {
pub fn helper() -> i32 { 42 }
mod child {
pub fn use_parent() -> i32 {
super::helper() // Access parent's function
}
}
}src/
├── main.rs
├── garden.rs // mod garden
└── garden/
└── vegetables.rs // mod garden::vegetablesFix the module visibility:
math::add publicmath::advanced::multiply_and_add publicsuper::add in multiply_and_addmath::add(5, 3) → 8math::advanced::multiply_and_add(2, 3, 4) → 10 (2*3 + 4)mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub mod advanced {
pub fn multiply_and_add(a: i32, b: i32, c: i32) -> i32 {
super::add(a * b, c)
}
}
}