Rust's module system helps organize code into logical units, control privacy, and manage scope. Here's a comprehensive guide to all the use cases.
Define modules directly in a file using the mod keyword:
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn private_helper() { // private by default
// ...
}
}
fn main() {
let result = math::add(2, 3);
}
Rust maps modules to the filesystem:
src/
├── main.rs
├── math.rs // mod math;
└── utils/
├── mod.rs // mod utils;
└── helpers.rs // mod helpers; (inside mod.rs)
In main.rs:
mod math; // looks for math.rs or math/mod.rs
mod utils; // looks for utils/mod.rs or utils.rs
use Keywordmod garden {
pub mod vegetables {
pub fn carrot() {}
pub fn potato() {}
}
}
// Different ways to use
use garden::vegetables::carrot; // specific item
use garden::vegetables::{carrot, potato}; // multiple items
use garden::vegetables::*; // glob import (use sparingly)
asuse std::collections::HashMap as Map;
use std::io::Result as IoResult;
let map: Map<String, i32> = Map::new();
pub useExpose nested items at a higher level:
mod internal {
pub mod deep {
pub fn utility() {}
}
}
pub use internal::deep::utility; // users can now call crate::utility()