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.
mod geometry { pub fn area(w: u32, h: u32) -> u32 { w * h } }
Try it
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.
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
[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.rswithmod net;, Rust looks forsrc/net.rsorsrc/net/mod.rs. Fornet.rscontainingmod tcp;, it looks forsrc/net/tcp.rs. Thename.rsplusname/folder layout is the modern style;mod.rsis still accepted. - Declare each module once.
mod x;is how a file joins the build. Writinguseor 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::andcrate::(seecrate,self,super) to name other items, anduseto import them. - Test modules.
#[cfg(test)] mod testsis compiled only forcargo test, and sees the parent's private items throughuse super::*;. - Re-exports with
pub uselet you present a different public layout from your file layout. - Not Java packages. A module is not tied to a directory by itself; the
moddeclaration is what creates it.
Related
use,pub,crate,selfandsuper,struct- Lessons: Modules, Cargo and projects, Testing