The Analogy: The Backstage Doors
A theatre looks like one building from the street and is really a set of nested areas: front of house, then the stage, then the workshop behind it, then the dressing-room corridor off to one side. Every one of those areas has a door, and none of those doors exists to keep the staff out. They exist so that a member of the audience who wanders through the wrong curtain finds a handle that does not turn.
The rule is asymmetric, and the asymmetry is the entire design. Someone standing in a dressing room can walk out into the corridor, and from there into the wing, and from there onto the stage -- outward is always allowed, because they are already inside. Someone standing in the auditorium cannot walk into a dressing room. Inner areas can reach out; outer areas cannot reach in.
When an inner area does want to be reachable, somebody screws a sign to the door: "Wardrobe -- collections this way". Now that door opens from the outside as well, and it opens for anybody who could already get as far as the corridor. That is the only mechanism there is, and it works one door at a time: a signed door into the wing tells you nothing at all about the unsigned doors deeper inside it.
The building plan by the fire exit is the other half of the story. It lets a stagehand say "the workshop is behind the stage, off the main corridor" instead of "turn left, then right, then second door" from wherever they happen to be standing. Rust gives you both -- doors with and without signs, and a plan you can name paths from. This lesson is about the doors.
Syntax or Core Structure
mod declares a module. Everything inside one is private to the outside world until you write pub.
mod theatre {
pub mod stage {
pub fn cue(number: u32) -> String {
format!("stage cue {number}: {}", house_style())
}
fn house_style() -> String {
String::from("lights up slow")
}
}
pub mod wardrobe {
pub fn fit(actor: &str) -> String {
format!("{actor} fitted from {}", rail())
}
fn rail() -> String {
String::from("rail 3")
}
}
pub fn call_the_half() -> String {
format!("half hour called; {}", stage::cue(0))
}
}
fn main() {
println!("{}", theatre::stage::cue(1));
println!("{}", theatre::wardrobe::fit("ada"));
println!("{}", theatre::call_the_half());
}
Output:
stage cue 1: lights up slow
ada fitted from rail 3
half hour called; stage cue 0: lights up slow
Read the visibility, not the nesting. theatre itself has no pub, and main can still reach it, because main lives in the crate root and theatre is one of the root's own items -- an item is private to the outside, and the module that declares it is not outside. stage and wardrobe do need pub, because main is asking theatre to let it in. And house_style has no pub at all, which is why stage::cue can call it and nothing else can.
Add one line to main that reaches for the unsigned door:
println!("{}", theatre::stage::house_style());
Output:
error[E0603]: function `house_style` is private
--> src/main.rs:9:36
|
9 | println!("{}", theatre::stage::house_style());
| ^^^^^^^^^^^ private function
|
note: the function `house_style` is defined here
(The note's own source snippet is trimmed above.) Notice what the error is not: it is not "no such function". Rust found house_style, resolved the whole path, and then refused on visibility grounds. That distinction matters when you are reading errors quickly -- E0603 means "it exists and you may not name it here", while E0425 means "there is nothing by that name".
Technical Depth: The Module Tree and Its Doors
Where a module's body lives
mod name { ... } puts the body inline. mod name; -- with a semicolon -- tells the compiler to go and find the body in a file, and the file it looks for depends on which file the declaration is in.
| Declaration | Where it appears | File the compiler loads |
|---|---|---|
mod stage { ... } | anywhere | nowhere, the body is inline |
mod stage; | src/main.rs or src/lib.rs | src/stage.rs |
mod stage; | src/main.rs or src/lib.rs | src/stage/mod.rs (older layout) |
mod lights; | src/stage.rs | src/stage/lights.rs |
mod lights; | src/stage/mod.rs | src/stage/lights.rs |
Two things follow from that table, and both surprise people. First, a .rs file that nothing declares is not part of your crate at all -- it is not compiled, its errors are not reported, and cargo build succeeds while ignoring it. Second, the two root layouts are alternatives, not both: if src/stage.rs and src/stage/mod.rs both exist the compiler stops with E0761, "file for module found at both", because it cannot know which one you meant.
The four privacy rules
- An item is private to everything outside the module that declares it.
- The declaring module and every module nested inside it can name the item,
pubor not. - A parent can not name a child's private items, even though the parent declared the child.
pubopens exactly one door. It says nothing about the doors on either side of it.
The second rule is the one that reads backwards at first. A child module sits deeper in the tree than its parent, so it is inside the parent, so the parent's private items are already in scope for it. Privacy in Rust runs outward-in, exactly like the dressing-room door.
The shades of pub
| Form | Who may name the item |
|---|---|
| nothing | the declaring module and its descendants |
pub | anyone who can reach the enclosing module |
pub(crate) | anywhere in this crate, never from another crate |
pub(super) | the parent module and everything under it |
pub(self) | the declaring module only, the same as writing nothing |
pub(in crate::a::b) | that named module and everything under it |
pub(crate) is the workhorse in real projects. A helper that three modules share is not part of your library's promise to the outside world, and marking it plain pub would put it in your public API where a later change becomes a breaking one.
pub on a struct is not pub on its fields
This is the single most common surprise, and structs and enums behave differently.
mod tickets {
pub struct Ticket {
pub seat: String,
price_pence: u32,
}
impl Ticket {
pub fn new(seat: &str, price_pence: u32) -> Ticket {
Ticket {
seat: String::from(seat),
price_pence,
}
}
pub fn price(&self) -> String {
format!("{}.{:02}", self.price_pence / 100, self.price_pence % 100)
}
}
pub enum Tier {
Stalls,
Circle,
Box { number: u32 },
}
pub fn tier_name(t: &Tier) -> String {
match t {
Tier::Stalls => String::from("stalls"),
Tier::Circle => String::from("circle"),
Tier::Box { number } => format!("box {number}"),
}
}
}
fn main() {
let t = tickets::Ticket::new("H14", 4250);
println!("seat {} at {}", t.seat, t.price());
let tiers = [
tickets::Tier::Stalls,
tickets::Tier::Circle,
tickets::Tier::Box { number: 2 },
];
for tier in &tiers {
println!("{}", tickets::tier_name(tier));
}
}
Output:
seat H14 at 42.50
stalls
circle
box 2
Ticket is pub, and seat is readable from main only because seat is also marked pub. Reaching for t.price_pence instead gives E0616, "field price_pence of struct Ticket is private" -- which is exactly the design you want here, because the pence are an implementation detail and price() is the promise. An enum is the opposite: pub enum Tier makes Stalls, Circle, Box and Box's number field all public in one stroke, and there is no syntax for a private variant. The reasoning is that a variant you cannot name is a variant you cannot match, and a partly-matchable enum would be useless.
The same asymmetry applies to a pub struct with a private field somewhere else: outside code cannot use struct literal syntax to build one, because it would have to name the private field. That is not a limitation, it is the standard way a library forces callers through a constructor.
Privacy is per module, not per file
Nothing above depends on files. Every program in this lesson is one main.rs, and the boundaries are still real: house_style is unreachable from main even though they are forty lines apart in the same file. This is why a mod tests block works the way it does:
struct Meter {
reading: u32,
}
impl Meter {
fn doubled(&self) -> u32 {
self.reading * 2
}
}
#[cfg(test)]
mod tests {
use super::Meter;
#[test]
fn doubles_the_reading() {
let m = Meter { reading: 21 };
assert_eq!(m.doubled(), 42);
}
}
tests is a child module, so it can reach Meter's private field and private method without either being marked pub -- a unit test gets at the internals precisely because it lives inside. The #[cfg(test)] attribute means the module is compiled only under cargo test, so it costs a release build nothing. Module 7 covers what goes inside those functions.
Real World Example: Splitting a Log Reader into Modules
Three jobs, three modules, one boundary each: parse turns text into values, stats reduces values to a summary, report turns a summary into a line of output. The comment above each mod is the file it would live in once the crate outgrows a single page.
// src/main.rs
mod log {
// src/log.rs, with a src/log/ folder beside it
pub mod parse {
// src/log/parse.rs
#[derive(PartialEq)]
pub enum Level {
Info,
Warn,
Error,
}
pub struct Entry {
pub level: Level,
pub route: String,
pub ms: u32,
}
fn level_of(word: &str) -> Option<Level> {
match word {
"INFO" => Some(Level::Info),
"WARN" => Some(Level::Warn),
"ERROR" => Some(Level::Error),
_ => None,
}
}
pub fn line(raw: &str) -> Option<Entry> {
let parts: Vec<&str> = raw.split_whitespace().collect();
match parts.as_slice() {
[level, route, ms] => match (level_of(level), ms.parse::<u32>().ok()) {
(Some(level), Some(ms)) => Some(Entry {
level,
route: String::from(*route),
ms,
}),
_ => None,
},
_ => None,
}
}
}
pub mod stats {
// src/log/stats.rs
pub struct Summary {
pub total: usize,
pub errors: usize,
pub slowest: Option<String>,
}
pub fn summarise(entries: &[super::parse::Entry]) -> Summary {
let mut errors = 0;
let mut slowest: Option<&super::parse::Entry> = None;
for e in entries {
if e.level == super::parse::Level::Error {
errors += 1;
}
let replace = match slowest {
None => true,
Some(best) => e.ms > best.ms,
};
if replace {
slowest = Some(e);
}
}
Summary {
total: entries.len(),
errors,
slowest: slowest.map(|e| format!("{} at {} ms", e.route, e.ms)),
}
}
}
pub mod report {
// src/log/report.rs
pub fn render(s: &super::stats::Summary) -> String {
let slowest = match &s.slowest {
Some(text) => text.clone(),
None => String::from("none"),
};
format!("{} lines, {} errors, slowest {}", s.total, s.errors, slowest)
}
}
}
fn main() {
let raw = [
"INFO /health 3",
"INFO /users 41",
"WARN /users 190",
"ERROR /checkout 512",
"ERROR /checkout 88",
"TRACE /users 5",
"INFO /users",
];
let mut entries = Vec::new();
let mut rejected = 0;
for text in raw {
match log::parse::line(text) {
Some(entry) => entries.push(entry),
None => rejected += 1,
}
}
let summary = log::stats::summarise(&entries);
println!("{}", log::report::render(&summary));
println!("rejected {rejected} malformed lines");
for e in &entries {
println!(" {:<10} {:>4} ms", e.route, e.ms);
}
}
Output:
5 lines, 2 errors, slowest /checkout at 512 ms
rejected 2 malformed lines
/health 3 ms
/users 41 ms
/users 190 ms
/checkout 512 ms
/checkout 88 ms
The boundaries here are load-bearing rather than decorative. level_of is private to parse, so no other module can grow a dependency on the exact spellings INFO, WARN and ERROR. The day the log format starts emitting lowercase levels, parse is the only module that changes, and the compiler can tell you that with certainty because nothing else was ever allowed to name that function. A boundary is not tidiness; it is a finite list of the places a change can reach.
Every pub in the program is a decision that had to be argued for. Entry's three fields are public because stats reads them and main prints two of them. Summary's three are public because report reads them. Level is a pub enum, which publishes all three variants whether you want that or not -- only Error is ever compared, so Info and Warn are public purely because Rust has no private variant to offer. That is worth noticing rather than glossing over: the enum's public surface is wider than its use.
The verbosity is real and it is the point of the next two lessons. super::parse::Entry appears three times inside stats, and super::stats::Summary once inside report, because a path is currently the only way one module can name another's types. That is the itch use scratches -- the same use super::Meter; that appeared in the test module earlier. Once you have it, stats opens with a single use super::parse::{Entry, Level}; and its bodies read like ordinary code with no path noise at all.
The honest limits. Summary.slowest is a pre-formatted String, which forces render to clone it; holding a &Entry instead would avoid both the format! and the clone, but it would put a lifetime parameter on Summary and tie every summary to the batch it was built from. Rejected lines are counted and not explained -- TRACE /users 5 and INFO /users fail for completely different reasons and the program cannot tell you which, because Option has no room to carry a reason. Module 5's Result is the fix. summarise takes a whole &[Entry], so the entire batch has to be in memory before any of it is summarised. And all of it sits in one file, which is the one thing a real crate shaped like this would not do; the layout comments are the instructions for undoing that, and undoing it changes no code except turning each mod x { ... } into mod x;.
Common Mistakes
- Creating the file and forgetting the
mod. You addsrc/stats.rs, write two hundred lines, andcargo buildsucceeds without compiling a single one of them. Nothing declared the module, so the file is not part of the crate -- its syntax errors are not even reported. The first symptom is usuallyE0433, "failed to resolve: use of undeclared crate or modulestats", which sends people hunting for a typo in the path when the missing piece ismod stats;in the parent.
- Writing
modand expecting an import.moddeclares a module and demands a body for it. Puttingmod util;insidesrc/parse.rsbecause you want the root'sutildoes not reach the existing module -- it declares a brand new one and goes looking forsrc/parse/util.rs, then fails withE0583, "file not found for moduleutil". Declaring is a one-time act in one place; naming from elsewhere is what paths anduseare for.
- Thinking
pub modpublishes the contents.pub mod stagemeans outsiders may say the wordstage. Everything inside it is still private until individually marked. This bites hardest when you make a modulepub, see the sameE0603you had before, and conclude thatpubis broken.
- Thinking
pub structpublishes the fields. It does not, and outside code cannot even build the struct with literal syntax if any field is private. Enums are the exception, not the rule -- do not generalise frompub enumtopub struct.
- Expecting a parent to see a child's private items. Declaring a module does not grant access to it.
theatrecannot callstage::house_styleany more thanmaincan; the nesting runs the other way.
- Having both
src/stage.rsandsrc/stage/mod.rs. Usually this happens mid-refactor, when you copy a file into the folder layout and forget to delete the old one. The build stops withE0761, "file for modulestagefound at both", and the fix is always to delete one -- the compiler will not guess.
- Putting the
modline in the wrong parent.mod lights;inmain.rsmakes the pathcrate::lightsand looks forsrc/lights.rs. The same line instage.rsmakes itcrate::stage::lightsand looks forsrc/stage/lights.rs. The module tree is built entirely from where the declarations sit, and a file in a folder is not automatically a child of anything.
- A
mod testswith no#[cfg(test)]. It compiles into every release build, drags whatever the tests use along with it, and anyasserthelper you wrote for tests becomes dead code in the shipped binary. The attribute is not optional politeness.
- Reaching for
pubwhen you meanpub(crate). In a library, every plainpubitem that is reachable from the root is part of your published API, and changing it later is a breaking change for your users. If two of your own modules need to share a helper,pub(crate)says exactly that and keeps the helper out of the promise.
Best Practices
- Let the module tree follow the shape of the problem, not the shape of your folder habits.
parse,statsandreportare three jobs;helpers,utilsandmiscare three places for things to hide. - Start every module inline.
mod x { ... }costs nothing, the boundary is already real, and you can see the whole design on one screen while it is still changing. Split it into a file the moment it stops fitting. - Default to private and add
pubone item at a time, with a reason you could say out loud. The first version of a module should be almost entirely private, and eachpubshould be a response to an actual caller. - Reach for
pub(crate)whenever the caller you are opening the door for is your own code. It keeps the item out of a library's published API, so a later rename is an internal change rather than a breaking one. - Keep struct fields private and expose methods, unless the struct is plain data with no invariant to protect. Private fields are what let you change a representation -- pence to a decimal type, a
Stringto an enum -- without touching a single caller. - Prefer the
src/thing.rsplussrc/thing/layout oversrc/thing/mod.rsin new code. It puts the module's own contents in a file named after the module, so your editor's tab strip does not fill up with identicalmod.rslabels. - Put unit tests in a
#[cfg(test)] mod testsin the same file as the code they cover. Being a child module is what gives them access to the internals, and#[cfg(test)]is what keeps them out of the release build. - Keep the tree shallow.
crate::log::parse::Entryis already four segments, and a fifth rarely earns its keep -- deep trees make every path long, which pushes people toward aliases that hide where things actually live.
Practice Exercises
- Sign one more door. Add a
box_officemodule to the theatre program with a privatefn float() -> u32returning a cash float and a publicfn open(cash: u32) -> Stringthat uses it. Havetheatre::call_the_halfreport the box office too. Then add a line inmainthat callsfloatdirectly, and read theE0603closely: note which path segment the carets sit under, and what that tells you about how far resolution got before it refused.
- Open the struct, then close it again. In the tickets program, make
price_pencepublic and deleteprice(), moving the formatting intomain. Then reverse the change and add apub fn with_discount(&self, off_pence: u32) -> Ticketinstead. Write down which version you would rather be holding on the day the price needs a currency alongside it, and why the private field is what makes that day cheap.
- Split the log reader into real files. Turn the Real World program into a five-file crate:
src/main.rscontainingmod log;,src/log.rscontaining threepub moddeclarations, andsrc/log/parse.rs,src/log/stats.rsandsrc/log/report.rsholding the bodies unchanged. Confirm the output is identical. Then delete onepub modline fromsrc/log.rsand predict the exact error before you runcargo build.
- Find the narrowest visibility that still compiles. In your split crate, change every
pubtopub(crate)and build -- it should all still work, becausemainis in the same crate. Now changeparse::linealone frompub(crate)topub(super)and build again. Explain from the four privacy rules why that one fails whilepub(crate)did not, and say which module could still call it.