liveBook · Manning

Module hierarchy

As explained in Refactoring to Rust

A module hierarchy is a nested organization of modules that represents parent and child relationships in source code.

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

How Refactoring to Rust covers it

How deep it goes
Explains file declarations, nested paths, re-exports, and visibility, stopping short of broader library architecture.
Examples
Uses a greeter split into input.rs, output.rs, and day_kind.rs, plus a forest crate with nested paths and re-exports.
What it assumes
Assumes basic Rust functions and imports, while teaching module files, paths, and visibility incrementally through a greeter.
What you can do after
Apply it via Rust mod, pub, pub(crate), and pub use declarations to structure code and expose deliberate interfaces.
How it connects
Connects modules with filesystem layout, crate roots, paths, visibility, re-exports, and public APIs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.