Sub topic 2
Modules and the Module Tree
This chapter covers how Rust groups code into modules, how those modules form a tree, and how that tree decides what name refers to what. It assumes you know basic Rust syntax (functions, structs, enums, Result), have a working grasp of ownership and borrowing, and can run cargo build and cargo run. Paths, use declarations, visibility rules, and splitting modules across files each get their own chapter. Here we focus on the tree itself.
What a module is
A module is a named container for items. Items are functions, structs, enums, traits, constants, type aliases, impl blocks, and other modules. You declare one with the mod keyword.
Modules do two jobs:
- They group related code under a name, so a large crate stays readable.
- They set boundaries. By default, everything inside a module is private to it. The module is the unit of privacy in Rust.
Here is a small inline module:
mod shapes {
pub struct Rect {
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn area(&self) -> u32 {
self.width * self.height
}
}
fn private_helper() -> u32 {
42
}
pub fn answer() -> u32 {
private_helper()
}
}
fn main() {
let r = shapes::Rect { width: 3, height: 4 };
println!("{}", r.area());
println!("{}", shapes::answer());
// shapes::private_helper(); // error: function `private_helper` is private
}The program prints 12 and then 42. Three details are worth noticing:
Rect, its fields,area, andanswercarrypub, somaincan use them.private_helperhas nopub. Code insideshapescan call it, which is whyanswerworks. Code outside cannot.mainrefers to items through the pathshapes::Rect. The::separator walks down into a module.
The module tree
Every crate has a root module, and every other module is a child of some module. The result is a tree. The compiler starts at the crate root file, which is src/main.rs for a binary crate or src/lib.rs for a library crate. That file's contents form an implicit module named crate.
Consider this code:
mod kitchen {
pub mod stove {
pub fn heat() {}
}
pub mod fridge {
pub fn cool() {}
}
fn tidy() {}
}
mod garden {
pub fn water() {}
}
fn main() {
kitchen::stove::heat();
kitchen::fridge::cool();
garden::water();
}Its tree looks like this:
Terms from family trees apply. stove and fridge are siblings. kitchen is the parent of both. crate is an ancestor of every module. These relationships matter for privacy, as the next section shows.
You can print nothing special to see the tree. It exists only in the compiler. Tools such as cargo doc render it as the nested module listing in the generated documentation.
Why the tree controls privacy
The privacy rule is short: an item is visible to the module that contains it and to that module's descendants. Marking an item pub widens that visibility, so ancestors and outsiders can see it too, as long as every module along the path is also reachable.
Two consequences follow, and both surprise newcomers.
First, a child can see its parent's private items. A parent cannot see its child's private items.
mod outer {
fn secret() -> u32 {
7
}
pub mod inner {
pub fn peek() -> u32 {
super::secret() + 1
}
}
}
fn main() {
println!("{}", outer::inner::peek());
}This prints 8. The inner module reaches up to outer::secret with super, which means "my parent module." Because inner is a descendant of outer, the access is allowed even though secret is private.
Second, pub on an item does not help if a module on the way to it is private. In the next example, the function is public, but its module is not:
mod a {
mod b {
pub fn f() {}
}
pub fn call_f() {
b::f(); // fine: b is a child of a
}
}
fn main() {
a::call_f();
// a::b::f(); // error: module `b` is private
}The path a::b::f fails because main cannot see b. A public function inside a private module is a normal pattern. The module hides its structure while a exposes selected functions.
Keywords for moving around the tree
Paths can start from three places:
| Start | Meaning | Example |
|---|---|---|
| `crate::` | The crate root. This is an absolute path within your crate. | `crate::kitchen::stove::heat()` |
| `self::` | The current module. | `self::helper()` |
| `super::` | The parent module. It can be chained. | `super::super::top_level()` |
A path with none of these prefixes is resolved relative to the current module, or to names already brought into scope. Absolute paths with crate:: are usually the better default. They keep working if you move the calling code to a different module, while relative paths break. Prefer super:: when two items are meant to move together, such as a test module and the code it checks.
Declaring modules: `mod` is not an import
A frequent mistake is treating mod like import in other languages. In Rust, mod name; or mod name { ... } adds the module to the tree. A file that exists on disk but has no mod declaration pointing at it is not part of the crate. The compiler never sees it.
For example, if you create src/utils.rs and call utils::clean() from main.rs without writing mod utils;, you get an error such as use of undeclared crate or module. The fix is to declare the module once, in its parent:
// src/main.rs
mod utils;
fn main() {
utils::clean();
}You declare each module exactly once. Elsewhere you refer to it by path.
Structs, enums, and what `pub` covers
pub applies item by item, and it behaves differently for different kinds of items.
- A
pub structis public, but its fields stay private unless each one is markedpub. Code outside the module cannot build such a struct with literal syntax if any field is private. - A
pub enummakes all of its variants public. You do not mark variants individually. - A
pub modexposes the module name. The items inside still need their ownpub.
The struct rule is useful. It lets a module enforce an invariant by forcing callers through a constructor:
mod account {
pub struct Balance {
cents: u64,
}
impl Balance {
pub fn new(cents: u64) -> Balance {
Balance { cents }
}
pub fn dollars(&self) -> u64 {
self.cents / 100
}
}
}
fn main() {
let b = account::Balance::new(2599);
println!("{}", b.dollars());
// let c = account::Balance { cents: 5 }; // error: field `cents` is private
}This prints 25. Because cents is private, no outside code can set it directly.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `module `x` is private` | A module on the path lacks `pub`. | Make the module `pub`, or expose the item some other way. |
| `function `f` is private` | The item lacks `pub` and the caller is outside its module. | Add `pub`, or call it from inside the module. |
| `failed to resolve: use of undeclared crate or module` | The module was never declared with `mod`, or the path is spelled wrong. | Add `mod name;` to the parent, and check the path. |
| `field `x` of struct is private` | Struct literal or field access from outside the module. | Provide a constructor or accessor, or mark the field `pub`. |
| `unused` warning for a module | Nothing uses its items. | Use it, remove it, or mark it `pub` in a library. |
A design habit
Organize modules around concepts, not around kinds of item. A module called account holding its types and functions is easier to navigate than modules named structs and functions. Keep modules small enough that their purpose fits in a sentence. When a module grows, split it into children, which is the subject of the file-splitting chapter.
Exercise
In the code below, which of the three lines in main fail to compile, and why?
mod store {
mod shelf {
pub fn stock() {}
}
pub fn open() {
shelf::stock();
}
fn close() {}
}
fn main() {
store::open();
store::close();
store::shelf::stock();
}
Show answer
The first line, store::open(), compiles. open is pub and store is a child of the crate root, so main can see it. The second line fails because close has no pub, so it is private to store. The third line fails because shelf has no pub, so main cannot see the module, even though stock itself is pub. Inside store, the call shelf::stock() works because shelf is a child of store.
Exercise
You add the file src/report.rs containing a public function print_all, then call report::print_all() from main. The compiler says it cannot find the module. What is missing, and where does it go?
Show answer
The module is not declared. Add mod report; to src/main.rs (the parent of the new module, here the crate root). Creating the file alone does not add it to the module tree.