Separating Modules into Different Files
As modules grow, separate them into individual files for better organization. Unlike JavaScript/TypeScript where files are implicit modules, Rust requires explicit module declarations.
Moving Modules to Files
Starting from inline modules, extract them to separate files:
mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
pub mod hosting {
pub fn add_to_waitlist() {}
}
The mod
declaration loads the file once—it’s not an “include” operation. Other files reference the loaded module via its declared path.
Extracting Submodules
For submodules, create a directory structure:
pub mod hosting;
pub fn add_to_waitlist() {}
The file location must match the module hierarchy—hosting
goes in src/front_of_house/hosting.rs
because it’s a child of front_of_house
.
File Path Conventions
Rust supports two file organization styles:
Modern style (recommended):
src/front_of_house.rs
src/front_of_house/hosting.rs
Legacy style (still supported):
src/front_of_house/mod.rs
src/front_of_house/hosting/mod.rs
Don’t mix styles within the same project to avoid confusion.
Summary
Rust’s module system provides explicit control over code organization and visibility:
- Packages contain crates with
Cargo.toml
manifests - Crates are compilation units (binary or library)
- Modules organize code with privacy controls (private by default)
- Paths address items using
::
syntax (absolute withcrate::
or relative) use
creates local shortcuts to reduce path repetitionpub
exposes items across module boundaries
This system enforces encapsulation at compile time, unlike JavaScript’s runtime-based privacy patterns.