A module hierarchy organizes Rust code into parent and child modules. The hierarchy can be written with nested mod blocks or distributed across files, but the compiler treats both forms as providing the same isolation. section 5.1.2
Rust does not infer the hierarchy from the filesystem alone. Each file relationship needs a mod declaration: a crate-root mod forest points to forest.rs, while mod bananas inside that module points to forest/bananas.rs. section 5.1.2
Use the hierarchy to keep implementation details organized and public interfaces manageable:
- Place substantial modules in their own files so developers can navigate directly to focused code. section 5.1.2
- Connect child modules with paths such as crate::day_kind::DayKind when referring to items through the hierarchy. section 5.2.2
- Use pub use to re-export selected items at a shorter public path, hiding deeply nested implementation structure from users. section 5.2.2
- Control which hierarchy members are exposed with private, pub(crate), and public visibility. section 5.2.2
A small greeter hierarchy
A crate root can declare mod day_kind, mod input, and mod output, while day_kind.rs defines DayKind and the other files use crate::DayKind. The root can re-export the enum with pub use day_kind::DayKind, giving internal code and external users a shorter path. section 5.1.2 section 5.2.2
Listing 5.5 Greeter program main.rs
use input::get_name;
use output::{goodbye, hello};
mod input; #1
mod output;
fn main() {
let name = get_name();
hello(&name);
goodbye(&name);
}
Inspect the crate-root declarations and imports in the greeter program to see how separate files form one module hierarchy. section 5.1.2
