Skip to main content
A Rust module is a namespace that encapsulates code items—such as functions, structs, traits, impl blocks, and other modules—to establish scope boundaries and control visibility. Modules form a hierarchical tree structure originating from a crate root (typically src/lib.rs or src/main.rs), allowing developers to partition code logically and manage namespace collisions.

Inline Module Declaration

Modules are defined using the mod keyword. An inline module contains its implementation directly within a block in the same file.

File System Mapping

When a module is declared without a code block, the Rust compiler (rustc) defers the module’s definition to an external file. The compiler resolves the module tree by looking for files that match the module’s name.
For the declaration mod parser;, Rust will look for the implementation in one of two locations relative to the declaring file:
  1. parser.rs
  2. parser/mod.rs
To extract submodules of parser into their own external files, a directory structure is required. If parser.rs contains the declaration mod ast;, the compiler will look for parser/ast.rs or parser/ast/mod.rs. However, inline submodules (e.g., mod ast { ... }) can be defined directly inside parser.rs without needing a new directory.

Visibility and Privacy Boundaries

By default, all items within a module (functions, structs, fields, methods, and submodules) are private. They are only visible to the module itself and its descendant submodules. The pub keyword modifies this visibility. Rust provides granular visibility modifiers to restrict access to specific scopes:
  • pub(in path) Semantic Rule: The path specified in a pub(in path) visibility modifier must be an ancestor module of the module where the item is defined.
  • Struct Field Visibility: Making a struct public (pub struct) does not automatically make its fields public. Fields must be individually marked with pub.

Path Resolution and Scope Import

To reference items across the module tree, Rust uses paths separated by the double colon ::. Paths can be absolute or relative.
  • crate:: initiates an absolute path from the crate root.
  • super:: initiates a relative path from the parent module.
  • self:: initiates a relative path from the current module.
The use keyword binds a full path to a local name, bringing the item into the current module’s scope to reduce verbosity.

Re-exporting (pub use)

Modules can re-export items from other modules using pub use. This flattens the public API, allowing external consumers to access deeply nested items as if they were defined in the re-exporting module.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More