Modules in Rust
| Declare mod | |
| Use paths | |
| pub walls | |
| Files mirror modules |
Declare mod
A mod block groups functions and types under one name. Code reaches inside with a path of two colons, which keeps large files organized by topic.
Start with inline modules in one file and split them into files once each topic grows its own tests and helpers.
mod kitchen {
pub fn cook() {
println!("yum");
}
}
fn main() {
kitchen::cook();
}
The kitchen module owns the cook function. Main calls it through the module path with no imports needed.
Use paths
Use brings a path into scope so later code can skip the prefix. Import the exact function or type used often and leave rare calls on their full path.
Place use lines near the top of the file so readers see outside dependencies at a glance.
mod kitchen {
pub fn cook() {
println!("yum");
}
}
use kitchen::cook;
fn main() {
cook();
}
After the import, main calls cook directly. The path still documents where the function lives for anyone reading the top of the file.
pub walls
Items stay private by default and pub opens them to the outside. Keep helpers private and mark only the planned entry points public, which shrinks the surface others can rely on.
The compiler stops outside calls to private items, so visibility mistakes surface as clear build errors.
mod kitchen {
fn secret() {}
pub fn cook() {
secret();
}
}
fn main() {
kitchen::cook();
}
Inside the module, cook can call the private secret helper. Outside code sees only cook, so the helper stays free to change.
Files mirror modules
Files mirror the module tree as projects grow. The file src/garden.rs holds the garden module declared in src/main.rs, which keeps each topic in its own file.
Declare mod garden once at the crate root and define the items inside the matching file, with submodules nesting one level deeper.
src/main.rs
src/garden.rs
Two files back one small tree. Move shared helpers into the module file and keep main focused on wiring the pieces together.
Next: Crates and workspaces
Article author: Arthur Isaev