The Analogy: Way-finding in a Big Hospital
A large hospital gives you directions in two completely different registers, and it needs both. Painted on the floor by the main lifts is a blue line with "Radiology" stencilled beside it. Follow it and you arrive. The line is short, it is easy to obey, and it is worthless the moment you are standing somewhere else -- there is no blue line in the car park, and the one on Level 5 leads somewhere different.
The other register is the one printed on your appointment letter: "Radiology, Level 2, Tower Block". That works from the car park, from the cafe, from Ward 11, from a taxi. It is longer to say and longer to read, and it never depends on where you happen to be standing.
Now watch what breaks each of them. The hospital reorganises and moves the whole Tower Block outpatient cluster one floor down: every appointment letter is wrong, and every blue line still works, because the lines were painted relative to junctions that moved with the departments. A year later they rename Tower Block to the Queen's Building: the letters are wrong again, and the lines are fine. But if you are the thing that moves -- your clinic relocates from Level 5 to the ground floor -- then your memorised "left at the lifts, second door" is wrong and the printed address is still perfect.
Rust has exactly these two registers. An absolute path starts from the crate root and is correct from anywhere you write it. A relative path starts from wherever it is written, and it is shorter for that reason. Neither is right; they fail under different kinds of change, and choosing between them is a bet about which change is coming.
Syntax or Core Structure
A path is a list of names separated by ::. It is absolute if it begins with crate, a crate name, or ::; it is relative if it begins with self, super, or a plain identifier.
mod records {
pub mod admissions {
pub fn ward_of(patient: u32) -> String {
format!("ward {}", (patient % 4) + 1)
}
pub fn summary(patient: u32) -> String {
let ward = ward_of(patient);
let bed = super::beds::bed_of(patient);
format!("patient {patient}: {ward}, {bed}")
}
}
pub mod beds {
pub fn bed_of(patient: u32) -> String {
format!("bed {}", (patient % 6) + 1)
}
}
}
fn main() {
println!("{}", crate::records::admissions::summary(7));
println!("{}", records::beds::bed_of(7));
println!("{}", self::records::admissions::ward_of(7));
}
Output:
patient 7: ward 4, bed 2
bed 2
ward 4
Three different paths, one module tree. Inside summary, ward_of(patient) is the shortest possible relative path -- a bare name, resolved in the module the line is written in -- while super::beds::bed_of has to climb out to records first, because beds is a sibling and siblings are not in each other's scope. In main, all three calls are equivalent in reach: main lives in the crate root, so crate::records, records and self::records name the same module by three different routes.
Climb one level too far and resolution stops before it ever considers visibility:
let bed = super::super::beds::bed_of(patient);
Output:
error[E0433]: failed to resolve: there are too many leading `super` keywords
--> src/main.rs:9:23
|
9 | let bed = super::super::beds::bed_of(patient);
| ^^^^^ there are too many leading `super` keywords
From admissions, one super reaches records and a second reaches the crate root -- which has no parent, so there is nowhere for the third step to go. The crate root is the ceiling, and super cannot punch through it into another crate.
Technical Depth: How a Path Is Resolved
The six openings, and where each one starts
| Path begins with | Kind | Resolution starts at |
|---|---|---|
crate | absolute | the root of the crate being compiled |
a crate name, e.g. std::fs | absolute | that crate's root |
::, e.g. ::std::fs | absolute | an external crate, never a local item |
self | relative | the module the path is written in |
super | relative | the parent of that module |
| a plain identifier | relative | the module the path is written in |
The last row is where most confusion lives. A bare records::beds::bed_of(...) does not mean "start at the root and look for records" -- it means "look for records here". It happens to work in main only because main is in the root, so "here" and "the root" are the same place. Move that identical line into admissions and it fails, because admissions has no child called records.
Which form to reach for
| Change you make | crate::records::beds::bed_of | super::beds::bed_of |
|---|---|---|
| move the caller to a different module | still correct | breaks |
| move caller and target together, as one subtree | breaks | still correct |
| rename an ancestor above both of them | breaks | still correct |
| rename the target's own module | breaks | breaks |
| read it cold in six months | tells you where the item lives | tells you where it lives from here |
The Rust book's recommendation is to prefer absolute paths, and the reason is a claim about frequency: definitions and their callers move independently more often than they move together. That is usually true, which makes it a good default -- but it is a default, not a law. Two modules that are genuinely one unit, and that you would always cut and paste together, are better off referring to each other with super::.
All four forms, in one function
mod site {
pub const NAME: &str = "north wing";
pub mod intake {
pub fn label() -> String {
String::from("intake")
}
pub mod desk {
pub fn where_am_i() -> String {
let a = crate::site::intake::label();
let b = super::label();
let c = self::helper();
let d = helper();
format!("{a} {b} {c} {d} in {}", super::super::NAME)
}
fn helper() -> String {
String::from("desk")
}
}
}
}
fn main() {
println!("{}", site::intake::desk::where_am_i());
}
Output:
intake intake desk desk in north wing
a and b reach the same function two ways; c and d reach the same function two ways. self::helper() and helper() are identical -- self in a path is almost always noise, and its one real use is disambiguation: if a use at the top of the module brought in a name that collides with a local item, self::name insists on the local one.
Paths name more than functions
mod records {
pub const CAPACITY: u32 = 40;
pub enum Status {
Waiting,
Seen,
Discharged,
}
pub struct Patient {
pub id: u32,
pub status: Status,
}
impl Patient {
pub fn new(id: u32, status: Status) -> Patient {
Patient { id, status }
}
}
}
fn main() {
let ward = [
records::Patient::new(3, records::Status::Seen),
records::Patient::new(4, records::Status::Waiting),
records::Patient::new(5, records::Status::Discharged),
];
for p in &ward {
let word = match &p.status {
records::Status::Waiting => "waiting",
records::Status::Seen => "seen",
records::Status::Discharged => "discharged",
};
println!("patient {} is {word}", p.id);
}
println!("ward capacity {}", records::CAPACITY);
}
Output:
patient 3 is seen
patient 4 is waiting
patient 5 is discharged
ward capacity 40
Six kinds of thing appear at the end of a path in real code: modules, functions, types (structs, enums, aliases), constants and statics, enum variants, and associated items such as Patient::new or u32::MAX. Traits and the fully qualified <Type as Trait>::method form join the list in Module 6.
One of those six has a rule worth memorising. An enum variant is always named through its enum, never through the module alone. records::Status::Seen resolves; records::Seen does not, because Seen is not an item of records -- it is an item of Status. The same is true in patterns, which is why every match arm above repeats records::Status::. That repetition is not a style failure, it is what a path costs, and the next lesson is about paying it once instead of five times.
Every path is checked twice
| Symptom | Code | What it means | What to change |
|---|---|---|---|
failed to resolve | E0433 | nothing of that name exists along that route | the path, or a missing mod declaration |
... is private | E0603 | it exists, you found it, the door is shut | add pub at the item it names |
cannot find value ... | E0425 | a bare name is not in scope at all | the spelling, or bring it in scope |
Resolution runs first and visibility runs second, so the code you get tells you which half failed. E0433 means your path is wrong. E0603 means your path is right and something along it needs opening -- and it names the specific item, which is more useful than it looks, because on a five-segment path only one segment is usually the culprit.
Naming your own crate, and other crates
From inside a crate, the root is spelled crate. Your package's own name is not a valid prefix for its own code -- mylib::helpers::tidy() written inside mylib does not resolve. That name only works from outside: from another crate that depends on you, and from your own integration tests in tests/, which are separate crates that link against your library. This catches people who move a function from an integration test into the library and wonder why the path stopped working.
Two smaller rules. A package named data-store is reached as data_store in paths, because hyphens are not legal in Rust identifiers and Cargo substitutes underscores. And a leading :: forces resolution to start at an external crate, which is the escape hatch for the day one of your own modules is called rand and you need the crate: ::rand is the dependency, self::rand is yours.
Real World Example: Routing Support Tickets Across Modules
A support desk with two collaborating modules under one parent. triage decides which queue a ticket belongs to; rota decides who owns that queue and how long they have. Every cross-module reference below is a path, and the forms are deliberately mixed so you can compare them side by side.
mod support {
pub const SLA_HOURS: u32 = 24;
pub mod triage {
pub enum Queue {
Billing,
Technical,
Account,
Unknown,
}
pub fn queue_of(subject: &str) -> Queue {
let lower = subject.to_lowercase();
if lower.contains("invoice") || lower.contains("refund") {
Queue::Billing
} else if lower.contains("crash") || lower.contains("error") {
Queue::Technical
} else if lower.contains("password") || lower.contains("login") {
Queue::Account
} else {
Queue::Unknown
}
}
pub fn queue_name(q: &Queue) -> &'static str {
match q {
Queue::Billing => "billing",
Queue::Technical => "technical",
Queue::Account => "account",
Queue::Unknown => "unknown",
}
}
}
pub mod rota {
pub fn owner_of(queue: &super::triage::Queue) -> &'static str {
match queue {
super::triage::Queue::Billing => "ravi",
super::triage::Queue::Technical => "mei",
super::triage::Queue::Account => "ada",
super::triage::Queue::Unknown => "duty",
}
}
pub fn deadline_hours(queue: &super::triage::Queue) -> u32 {
match queue {
super::triage::Queue::Technical => crate::support::SLA_HOURS / 4,
super::triage::Queue::Unknown => crate::support::SLA_HOURS * 2,
_ => super::SLA_HOURS,
}
}
}
pub fn route(subject: &str) -> String {
let queue = triage::queue_of(subject);
let name = triage::queue_name(&queue);
let owner = rota::owner_of(&queue);
let hours = rota::deadline_hours(&queue);
format!("{name:<10} {owner:<5} {hours:>2}h")
}
}
fn main() {
let subjects = [
"Invoice 4021 is wrong",
"App crash on startup",
"Cannot reset my password",
"Do you ship to Orkney?",
"Refund for duplicate charge",
"Login error after update",
];
for s in subjects {
println!("{} {}", support::route(s), s);
}
println!();
println!("default SLA {} hours", support::SLA_HOURS);
}
Output:
billing ravi 24h Invoice 4021 is wrong
technical mei 6h App crash on startup
account ada 24h Cannot reset my password
unknown duty 48h Do you ship to Orkney?
billing ravi 24h Refund for duplicate charge
technical mei 6h Login error after update
default SLA 24 hours
Three forms sit in one file. route writes triage::queue_of and rota::owner_of with no prefix at all, because it lives in support alongside both -- that is the shortest path available anywhere in the program. rota writes super::triage::Queue, climbing out to support and back down, because a sibling module is never in scope. And deadline_hours reaches one constant by two routes, crate::support::SLA_HOURS and super::SLA_HOURS, which resolve to the same item -- proof that choosing a form is about resilience and readability, not about reach.
The cost lands in rota. super::triage::Queue::Technical is five segments to name one variant, and owner_of repeats the first three of them on every single arm: a function whose real content is four owner names carries more prefix than payload. Nothing here is written badly. A path is simply a poor tool for repetition, and that is exactly the gap the next lesson fills.
Run the move test on this file and the trade-off stops being abstract. Lift rota out of support up to the crate root: every super::triage::Queue in it breaks, and crate::support::SLA_HOURS keeps compiling untouched. Now instead rename support to helpdesk: the super:: paths are all still correct and the two crate::support:: paths are not. Absolute wins as a default because moving one definition is more common than renaming a shared ancestor -- but if triage and rota are genuinely one unit that you would always relocate together, super:: is an honest statement of that coupling and deserves to stay.
The honest limits. Login error after update lands in the technical queue because the else if chain tests "error" before "login" and the first match wins -- keyword priority is real routing policy hidden inside control flow, and a production router would score every keyword and take the highest rather than short-circuit on the first hit. to_lowercase allocates a fresh String for every subject, which is invisible at six tickets and measurable at six million. The deadlines are derived from SLA_HOURS by / 4 and * 2, so all three move together when the constant changes: a feature if the ratios are the policy, a bug if the six-hour technical target was agreed separately. And owner_of can return &'static str only because the rota is hard-coded in the source; a rota loaded from a file would have to return an owned String or a borrow tied to whatever holds the data.
Common Mistakes
- Reading a bare path as if it started at the root. This is the big one.
records::beds::bed_of(7)works inmainand fails the instant you paste it intoadmissions, because a plain identifier is resolved in the module the line is written in. The line did not change; its meaning did. If you want a path whose meaning does not depend on where it sits, it has to start withcrate.
- Expecting a sibling to be in scope. Declaring
bedsandadmissionsnext to each other insiderecordsdoes not introduce them to one another. Fromadmissions,bedsis reached by going up first:super::beds, orcrate::records::beds. Nesting gives you access to ancestors, never to siblings.
- Stacking
superpast the root. The crate root has no parent, so a second or thirdsuperfrom a shallow module is a resolution error rather than a reach into the wider world. If you are countingsupers to get somewhere, that is the signal to write an absolute path instead -- two is already hard to read and three is always a mistake waiting to happen.
- Naming an enum variant through its module.
records::Seendoes not resolve;records::Status::Seendoes. The variant belongs to the enum, not to the module the enum lives in, and this applies in patterns exactly as it does in expressions.
- Treating
E0433andE0603as the same problem. They call for opposite fixes.E0433means the route is wrong, so change the path or add the missingmoddeclaration; sprinklingpubwill not help.E0603means the route is right, so leave the path alone and open the specific item the error names.
- Using your own package name inside your own crate. In a crate called
inventory, writinginventory::stock::count()from withinsrc/stock.rsfails. Inside the crate the root iscrate; the package name is how other crates address you. It bites most often when moving code out oftests/, where the package name was the correct prefix, intosrc/, where it is not.
- Forgetting that hyphens become underscores. A dependency declared as
serde-jsonor a package nameddata-storeis spelledserde_jsonanddata_storein every path, because-is not legal in a Rust identifier. Cargo does the conversion silently, so theCargo.tomlline and theuseline genuinely differ.
- Thinking
crate::spans a workspace. It does not:crateis the single crate currently being compiled. A sibling crate in the same workspace is an ordinary dependency -- list it inCargo.toml, then name it by its underscored package name.crate::other_crate::thingisE0433every time.
- Writing
self::out of habit.self::helper()andhelper()are the same path. Writing the prefix everywhere adds noise and, worse, tells every future reader that there is a name collision to go looking for. Use it only when there genuinely is one.
Best Practices
- Default to absolute paths, starting with
crate, for anything that crosses a module boundary. It is the form that survives the most common kind of change -- moving one definition -- and it tells a reader where the item lives without them having to work out where they are. - Reach for
super::when the two modules are genuinely one unit that you would always relocate together. That is a real design statement, so make it deliberately rather than becausesuper::was shorter to type. - Never write
self::unless it is disambiguating a real collision. It is a no-op otherwise, and it sends readers hunting for a shadowed name that does not exist. - Keep paths short by keeping the module tree shallow, not by hiding depth behind aliases. If a path has six segments, the tree is usually the thing to fix.
- Name enum variants through the enum, always. When the repetition starts to hurt in a match, that is a signal to bring the enum into scope with
use, not a reason to flatten your modules. - When you move a module, let the compiler drive. Every path it rejects is a place that depended on the old location, and that list of errors is the most honest coupling report you will ever get for free -- read it before you fix it.
- Read the error code before the message.
E0433sends you to the path;E0603sends you to apub;E0425sends you to the spelling. Two seconds of triage saves several minutes of editing the wrong thing. - Reserve a leading
::for the one case it exists to solve -- a local module that shares a name with a dependency. And do not carryextern crateforward from older examples: dependencies listed inCargo.tomlare already nameable, and the keyword has been unnecessary since the 2018 edition.
Practice Exercises
- Write the same function twice. Take
where_am_iand rewrite it so every path is absolute, then again so every path is relative. Confirm both print the identical line. Now movedeskup to be a direct child ofsiterather than ofintake, and see which of the two versions still compiles unchanged. Write down, in one sentence, what that experiment measures.
- Provoke all three codes on purpose. In the hospital program, produce an
E0433(callbeds::bed_offromadmissionswith nosuper), anE0603(makebed_ofprivate and call it frommain), and anE0425(callbed_ofwith no path at all frommain). Read each message and note which part of the path the carets sit under in each case.
- Count the coupling. In the support desk program, move
rotaout ofsupportand up to the crate root, changing nothing else. Build, and count how many paths the compiler asks you to fix. Fix them all with absolute paths. Then say what that number told you about how tiedrotawas to its old position -- and whether the same number would have appeared if every path inrotahad been absolute from the start.
- Reach in from outside with absolute paths only. Add a root-level
mod auditwithpub fn tally(subjects: &[&str]) -> Stringthat counts how many tickets land in each queue, using onlycrate::support::triage::queue_ofandcrate::support::triage::queue_name. Before you compile, write down everypubalong that path that has to already be in place for it to resolve, and which single missing one would give youE0603instead of a clean build.