Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The mod keyword

Reference for Rust mod: inline modules, file-based modules, mod.rs versus named files, #[path], privacy rules, nested modules and test modules with cfg(test).

mod declares a module: a named namespace that groups items such as functions, types and other modules. Modules form a tree rooted at the crate, and they are the unit of privacy: by default everything inside a module is private to that module and its descendants.

A module can be written inline with braces, or declared with mod name; so that the compiler loads its body from a file.

Rust
mod geometry {
    pub fn area(w: u32, h: u32) -> u32 { w * h }
}

Try it

Rust Inline modules and privacy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust The compiler enforces privacy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
[pub] mod name { items }        // inline
[pub] mod name;                 // body in name.rs or name/mod.rs
#[path = "other/file.rs"] mod name;
#[cfg(test)] mod tests { ... }
Part Description
mod name; Loads the module from name.rs or name/mod.rs next to the declaring file (for main.rs, lib.rs and mod.rs), or inside a folder named after the current module for other files.
Visibility pub, pub(crate), pub(super) and pub(in path) control who can see the module name.
Attributes #[path], #[cfg(...)], #[allow(...)] and inner #![...] attributes at the top of the module body.

Usage notes

  • Files and modules. For src/lib.rs with mod net;, Rust looks for src/net.rs or src/net/mod.rs. For net.rs containing mod tcp;, it looks for src/net/tcp.rs. The name.rs plus name/ folder layout is the modern style; mod.rs is still accepted.
  • Declare each module once. mod x; is how a file joins the build. Writing use or a path alone never compiles a file.
  • Privacy rule. Items are visible to the module where they are defined and its children. A parent cannot see a child's private items; a child can use its parent's private items through super::.
  • Paths. Inside a module use self::, super:: and crate:: (see crate, self, super) to name other items, and use to import them.
  • Test modules. #[cfg(test)] mod tests is compiled only for cargo test, and sees the parent's private items through use super::*;.
  • Re-exports with pub use let you present a different public layout from your file layout.
  • Not Java packages. A module is not tied to a directory by itself; the mod declaration is what creates it.