The Analogy: The Speed Dial List
A desk phone in a large office has two ways to reach anybody. You can key in the full number -- area code, exchange, extension -- and it always works, from any handset in the building, for as long as that person keeps that line. Or you can press button 3, because someone sat down once and programmed button 3 to mean that number.
The speed dial does not move the person. They are still in their office, still on the same extension, still reachable by the full number by anyone who cares to dial it. All that exists is a short local name for a long fixed address, and the shortness is the entire benefit.
The list belongs to the handset, not to the building. Button 3 on your phone means the warehouse; button 3 in the meeting room means catering; a phone nobody has programmed has no shortcuts at all. And when two people you call are both named Ravi, you cannot give them the same label -- one of them gets written on the card as "Ravi (accounts)", which is a decision you make locally and which nobody else has to agree with.
Reception is the interesting case. Reception publishes a printed list -- "these are the numbers worth having" -- and every new desk copies it. That is a promise: those numbers are the ones the building intends you to use, and if an extension changes, reception updates the list rather than letting everybody's card go stale. Rust has all four of these: the full address, the local shortcut, the local relabelling, and the published list.
Syntax or Core Structure
use brings a path into scope under its last segment, so you can stop repeating the path.
mod records {
pub mod beds {
pub struct Bed {
pub number: u32,
pub occupied: bool,
}
pub fn free_bed(beds: &[Bed]) -> Option<&Bed> {
for b in beds {
if !b.occupied {
return Some(b);
}
}
None
}
}
}
use crate::records::beds::Bed;
use crate::records::beds::free_bed;
fn main() {
let ward = [
Bed { number: 1, occupied: true },
Bed { number: 2, occupied: true },
Bed { number: 3, occupied: false },
Bed { number: 4, occupied: false },
];
match free_bed(&ward) {
Some(b) => println!("next free bed is {}", b.number),
None => println!("the ward is full"),
}
println!("{} beds on the ward", ward.len());
}
Output:
next free bed is 3
4 beds on the ward
Two things are worth being precise about. First, use moved nothing: Bed still lives at crate::records::beds::Bed, that path still works, and the use line only added a second, shorter name for it in this one module. Second, use is not permission. Both items are pub; if Bed were private, adding a use for it would produce the same E0603 as before, because a shortcut to a locked door is still a locked door.
The shortcut is also strictly local. Add a module to the same file and the name does not follow it in:
use crate::records::beds::Bed;
mod audit {
pub fn count(beds: &[Bed]) -> usize {
beds.len()
}
}
Output:
error[E0412]: cannot find type `Bed` in this scope
--> src/main.rs:9:26
|
9 | pub fn count(beds: &[Bed]) -> usize {
| ^^^ not found in this scope
|
help: consider importing this struct
audit is a child of the crate root, and children do not inherit a parent's scope. Bare names never fall through the module tree -- audit needs its own use line (or a full path), exactly like a phone nobody has programmed. This is the whole reason use super::*; appears at the top of almost every mod tests block you will ever read.
Technical Depth: Every Form of use
The forms
| Written | Brings into scope |
|---|---|
use crate::a::b; | the name b |
use crate::a::{b, c}; | b and c |
use crate::a::b as bee; | b, under the local name bee |
use crate::a::{self, b}; | the module a and the item b |
use crate::a::b::{self, c}; | b itself and b::c |
use crate::a::*; | every public item of a, all at once |
pub use crate::a::b; | b here, and publishes b at this location too |
The self form is the one people forget exists. use std::io::{self, Write}; gives you both io and Write, so you can write io::stdout() and call Write methods without two separate lines.
The convention: types by name, functions by parent
mod records {
pub mod beds {
pub fn count_free(occupied: &[bool]) -> usize {
let mut n = 0;
for &o in occupied {
if !o {
n += 1;
}
}
n
}
}
pub mod wards {
pub struct Ward {
pub name: String,
pub occupied: Vec<bool>,
}
}
}
use crate::records::beds;
use crate::records::wards::Ward;
fn main() {
let wards = [
Ward {
name: String::from("acute"),
occupied: vec![true, true, false],
},
Ward {
name: String::from("day"),
occupied: vec![false, false],
},
];
for w in &wards {
println!("{:<6} {} free", w.name, beds::count_free(&w.occupied));
}
}
Output:
acute 1 free
day 2 free
Two imports, deliberately different. Ward comes in by name, because a type appears in signatures and struct literals where wards::Ward would be noise, and because Ward alone is already unambiguous. count_free does not come in by name -- the module does, so the call site reads beds::count_free(...). That single extra segment is the whole point: a bare count_free(&w.occupied) gives a reader no clue that the function is defined a hundred lines away in another module, while beds::count_free says where to look. This is the Rust community's convention rather than a rule, and it earns its keep in code review.
as when two names collide
Two modules both call their error type Error. Importing both by name is impossible, so one or both get relabelled:
mod parse {
pub enum Error {
Empty,
NotANumber,
}
}
mod net {
pub enum Error {
Timeout,
Refused,
}
}
use crate::net::Error as NetError;
use crate::parse::Error as ParseError;
fn describe_parse(e: &ParseError) -> &'static str {
match e {
ParseError::Empty => "empty input",
ParseError::NotANumber => "not a number",
}
}
fn describe_net(e: &NetError) -> &'static str {
match e {
NetError::Timeout => "timed out",
NetError::Refused => "connection refused",
}
}
fn main() {
let problems = [
describe_parse(&ParseError::Empty),
describe_parse(&ParseError::NotANumber),
describe_net(&NetError::Timeout),
describe_net(&NetError::Refused),
];
for p in problems {
println!("{p}");
}
}
Output:
empty input
not a number
timed out
connection refused
as is the right tool here, but it is not the only one, and often not the best one. The alternative is to import the two parents -- use crate::net; and use crate::parse; -- and then write net::Error and parse::Error. That reads better than an invented alias, because ParseError is a name you made up and parse::Error is the name the code actually has. Reserve as for cases where even the parent names collide, or where the qualified form would be genuinely unwieldy.
pub use: publishing a shorter path
A plain use is a private item -- your shortcut, nobody else's. pub use makes the shortcut part of what others can reach, which turns it into an API design tool:
pub mod api {
pub use crate::internals::engine::Job;
pub use crate::internals::engine::run;
}
mod internals {
pub mod engine {
pub struct Job {
pub name: String,
pub minutes: u32,
}
pub fn run(job: &Job) -> String {
format!("{} took {} min", job.name, job.minutes)
}
}
}
fn main() {
let j = api::Job {
name: String::from("backup"),
minutes: 12,
};
println!("{}", api::run(&j));
}
Output:
backup took 12 min
Look at what that bought. internals is a private module -- nothing outside this crate could ever name it -- and yet api::Job works, because pub use re-exported an item out of a private module into a public one. Callers see a two-segment path and a tidy surface; you keep an internal tree you can rearrange at will. This is not a trick, it is how the standard library is built: HashMap is defined in std::collections::hash_map and re-exported at std::collections::HashMap, which is the only path anybody writes.
Glob imports, and where they are acceptable
use crate::a::*; pulls in every public item of a at once. It saves typing and costs you the ability to answer "where did this name come from", which is the question you will be asking at 6pm on the day something breaks. Worse, a glob can shadow silently: the prelude that gives you Option, None and String is itself glob-like and has the lowest precedence, so a glob of your own that happens to define None quietly wins.
There are two places globs are genuinely idiomatic. The first is use super::*; at the top of a #[cfg(test)] mod tests block, where you want everything from the module under test and the scope is one small block. The second is a module deliberately named prelude, where a library curates a set of names and documents that you are meant to glob it. Everywhere else, spell the names out.
use is also block-scoped, not file-scoped. A use written inside a function body applies to that body only and disappears at the closing brace, which is occasionally the tidiest way to pull in a trait needed by three lines of code.
Real World Example: The Support Desk, Rewritten with use
This is the ticket router from the previous lesson, with an escalation module added and every repeated path collapsed. Compare rota here against the version that wrote super::triage::Queue::Billing in every arm.
mod support {
pub use crate::support::triage::Queue;
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 {
use super::triage::Queue;
use super::SLA_HOURS;
pub fn owner_of(queue: &Queue) -> &'static str {
match queue {
Queue::Billing => "ravi",
Queue::Technical => "mei",
Queue::Account => "ada",
Queue::Unknown => "duty",
}
}
pub fn deadline_hours(queue: &Queue) -> u32 {
match queue {
Queue::Technical => SLA_HOURS / 4,
Queue::Unknown => SLA_HOURS * 2,
_ => SLA_HOURS,
}
}
}
pub mod escalation {
use super::rota::deadline_hours;
use super::triage::Queue;
pub enum Level {
None,
Manager,
Director,
}
pub fn level_for(queue: &Queue, hours_open: u32) -> Level {
let limit = deadline_hours(queue);
if hours_open <= limit {
Level::None
} else if hours_open <= limit * 2 {
Level::Manager
} else {
Level::Director
}
}
pub fn name_of(level: &Level) -> &'static str {
match level {
Level::None => "-",
Level::Manager => "manager",
Level::Director => "director",
}
}
}
pub fn line(subject: &str, hours_open: u32) -> String {
let queue = triage::queue_of(subject);
let level = escalation::level_for(&queue, hours_open);
format!(
"{:<10} {:<5} {:>3}h {:<8} {}",
triage::queue_name(&queue),
rota::owner_of(&queue),
hours_open,
escalation::name_of(&level),
subject
)
}
}
use crate::support::triage;
use crate::support::{line, Queue, SLA_HOURS};
fn main() {
let tickets = [
("Invoice 4021 is wrong", 6),
("App crash on startup", 5),
("Cannot reset my password", 30),
("Do you ship to Orkney?", 100),
("Refund for duplicate charge", 40),
("Login error after update", 14),
];
for (subject, hours) in tickets {
println!("{}", line(subject, hours));
}
println!();
let mut technical = 0;
for (subject, _) in tickets {
let q: Queue = triage::queue_of(subject);
if triage::queue_name(&q) == "technical" {
technical += 1;
}
}
println!("{technical} of {} tickets are technical", tickets.len());
println!("default SLA {SLA_HOURS} hours");
}
Output:
billing ravi 6h - Invoice 4021 is wrong
technical mei 5h - App crash on startup
account ada 30h manager Cannot reset my password
unknown duty 100h director Do you ship to Orkney?
billing ravi 40h manager Refund for duplicate charge
technical mei 14h director Login error after update
2 of 6 tickets are technical
default SLA 24 hours
Look at what changed and what did not. rota used to spell super::triage::Queue::Billing on every single arm; it now spells Queue::Billing, and the entire difference is one use super::triage::Queue; at the top of the module. The enum did not move. crate::support::triage::Queue is still its one and only definition, and the previous lesson's version of rota would compile perfectly well sitting next to this one. That is the property that makes use safe to add at any time: it is a naming change and nothing else.
The import styles are chosen rather than accidental. Queue and SLA_HOURS enter main by name, because a type in a let annotation and a constant inside a format string both read better short. triage enters as a module, so triage::queue_of(subject) still tells a reader where that function lives. Inside escalation the file bends its own convention once -- use super::rota::deadline_hours; imports a function by name -- and it is worth being honest that this is a judgement call: the function is called exactly once, on a line whose result is called limit, so the origin is not really in doubt. Conventions are for the cases where they help.
The pub use line at the top of support is API design compressed into one statement. Queue is defined in triage, and re-exporting it publishes a second path, crate::support::Queue, which is the one main imports. Callers get a short path and support keeps the freedom to move the enum into some other submodule later without breaking any of them. The cost is real though: two public paths now exist for one type, and both of them are promises you have to keep working.
The honest limits. The keyword-priority bug from the previous lesson is completely untouched -- Login error after update still lands in the technical queue, because "error" is tested before "login". That is the correct outcome for a change that only renames things, and it is a useful reminder that tidying imports improves no behaviour whatsoever. Level::None reuses a name the prelude already gives to Option; nothing breaks here because every use of it is qualified, but a single use crate::support::escalation::Level::*; anywhere in the file would make a bare None mean Level::None, and would do it without a warning. The escalation thresholds are limit and limit * 2, so a queue with a tight deadline escalates sooner in absolute hours -- intentional here, and exactly the kind of policy that belongs in data rather than in arithmetic. And to_lowercase allocates a fresh String per subject, now twice per ticket, because main re-triages every subject a second time just to count the technical ones.
Common Mistakes
- Assuming a
useat the top of the file covers the file. It covers the module it is written in. Amod something { ... }block further down the same file is a separate scope and needs its own imports. This is whyuse super::*;is the first line of nearly every#[cfg(test)] mod testsblock in the ecosystem -- the test module cannot see the imports sitting twenty lines above it.
- Expecting
useto open a private door.useintroduces a name; it grants nothing. If the item is private you getE0603with or without the import, and adding moreuselines will never change that. The fix is always apubat the item, in the module that defines it.
- Reaching for a glob because the list got long.
use crate::a::*;destroys your ability to answer "where is this name from" and can shadow prelude names silently. A long explicit list is a feature -- it is a readable dependency manifest for the module. Keep globs touse super::*;in tests and to modules explicitly namedprelude.
- Importing two items that end in the same name.
use crate::net::Error;next touse crate::parse::Error;isE0252, "the nameErroris defined multiple times". Fix it withas, or better, import the two parent modules and writenet::Errorandparse::Error.
- Importing a name you already define locally. A
use crate::other::Config;in a module that also declaresstruct ConfigisE0255-- the same message as the previous mistake, a different code, and the same two fixes. Rust has no notion of auselosing to a local item; it simply refuses.
- Importing functions by name until call sites stop saying anything.
run(&job),send(&msg)andcheck(&x)all look local and none of them are. Import the parent module instead and let the one extra segment do the documenting. Types are the opposite case, which is why the convention has two halves.
- Leaving unused imports behind after a refactor. They are only warnings, and that is the danger: a build with thirty
unused importwarnings is a build where nobody reads warnings, which is where a real one goes to hide.cargo fixremoves them for you.
- Thinking
pub userelocates the item. It adds a path. If the original path was public it stays public, so you now maintain two, and a caller may be depending on either. Deliberately narrowing the internals topub(crate)after adding a facade is what makes the re-export worth having.
- Writing
usepaths that start with a bare module name.use records::beds::Bed;happens to work in the crate root, because the first segment of ausepath is resolved in the current module. Move that identical line into a submodule and it fails, since the submodule has no child calledrecords. Startusepaths withcrate,super, or a crate name and the line means the same thing wherever it sits.
Best Practices
- Bring types, traits and enums into scope by name, and bring functions in through their parent module.
HashMap::new()andbeds::count_free(...)are both idiomatic for the same reason: each one puts the useful information at the call site and leaves out the noise. - Start every
usepath withcrate,superor a crate name. Auseline that begins with a bare module name changes meaning when you move it, which is the one property you never want in an import. - Prefer importing two parent modules over inventing two aliases.
net::Errorandparse::Errorare names your code already has;NetErrorandParseErrorare names you made up and now have to teach everyone. - Keep globs to two places:
use super::*;inside#[cfg(test)] mod tests, and modules a library documents as aprelude. Anywhere else, an explicit list is the module's dependency manifest and worth its length. - Design your library's front door with
pub usein the crate root, then tighten the internals it re-exports down topub(crate). A facade you did not narrow behind is just a second name for the same public API. - Remember that a plain
useis private. If you want callers to be able to write the short path too, theuseitself needspub. - Let
cargo fmtgroup and order imports, and clear unused ones out as you go withcargo fix. Import blocks are the part of a file people diff most often, so a machine-stable order saves real review time. - Reach for a scoped
useinside a function or block when a trait or type is needed by three lines and nowhere else. It keeps the module's import list about the module rather than about one corner of it.
Practice Exercises
- Collapse the log reader. Take the three-module log program from the "Organizing Code with Modules" lesson and add
usedeclarations so thatstatsno longer writessuper::parse::Entryandreportno longer writessuper::stats::Summary. Confirm the output is byte-for-byte identical, then count how many characters the imports removed and how many they added. Decide whether the trade was worth it for a module that referenced the type three times.
- Collect the three collisions. Deliberately produce an
E0252(importErrorfrom bothnetandparse), anE0255(import a name that the module also declares itself), and anE0603that nouseline can fix. For each one, write down in a sentence what the compiler is actually objecting to -- and note that the first two print the same message under different codes.
- Build a facade and then close the door. In the support desk program, add a root-level
pub mod apithat re-exportsline,QueueandSLA_HOURSwithpub use. Then changemod supportfrompubto private and see how much still compiles. Whatever breaks, fix it by re-exporting throughapirather than by puttingpubback, and describe what your crate's public surface looks like at the end.
- Run the glob experiment. Add
use crate::support::escalation::Level::*;to the top of the support desk file, then writelet l = None;insidemainfollowed byprintln!("{}", l.is_none());. Report exactly what the compiler says, work out whichNonethe bare name resolved to, and explain why this is the strongest argument against glob imports even though the glob itself compiled fine.