Skip to main content
A nested module in Rust is a module defined within the lexical scope of another module, establishing a hierarchical namespace tree for code organization and encapsulation. Nested modules create strict privacy boundaries, requiring explicit visibility modifiers to expose internal items to parent or external scopes.

Inline Declaration

Nested modules can be defined inline within a single file using nested mod blocks. By default, a nested module and its contents are private to its immediate parent module.

Visibility and Privacy Rules

Rust enforces strict privacy rules across module boundaries. A parent module cannot access private items within its nested child modules, but a nested child module can access all items (public or private) in its parent module. To control access, Rust provides granular visibility modifiers:
  • pub: Makes the item visible to any scope that can access the module.
  • pub(super): Restricts visibility to the immediate parent module.
  • pub(crate): Restricts visibility to the current crate.
  • pub(in path): Restricts visibility to a specific ancestor module defined by the provided path (e.g., pub(in crate::outer::inner)).

File System Mapping

When codebases grow, nested modules are typically extracted into separate files. Rust maps the module hierarchy to the directory structure. To nest a module via the file system, the parent module must declare the child module using mod child_module; without a block. Given the following module tree: crate::parent::child Directory Structure:
File Contents:
Note: In older Rust editions (pre-2018), src/parent.rs would instead be named src/parent/mod.rs.

Path Resolution

Navigating nested module trees requires specific path keywords:
  • Absolute paths begin from the crate root using the crate keyword.
  • Relative paths begin from the current module using self, super, or the identifier of a sibling module.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More