Modules, Paths and Privacy
The library program started as one file. Now it has a catalogue, loans, members and reports, and scrolling to find anything takes longer than writing it. Rust's module system lets you split code into named parts, and it decides exactly which parts the rest of the program is allowed to touch.
The rule
Modules form a tree; everything is private until marked
pub;useshortens paths.
A crate is one unit the compiler builds: a binary (starting at src/main.rs) or a library (starting at src/lib.rs). A package can hold one library and any number of binaries.
Modules divide a crate into a tree. Declare one inline, or in its own file:
// src/main.rs
mod catalogue; // loads src/catalogue.rs (or src/catalogue/mod.rs)
fn main() {
let book = catalogue::Book::new("Iron Tides", 380);
}// src/catalogue.rs
pub struct Book {
pub title: String,
pages: u32, // private field
}
impl Book {
pub fn new(title: &str, pages: u32) -> Book {
Book { title: title.to_string(), pages }
}
}
fn tidy(title: &str) -> String { title.trim().to_string() } // privateA module inside catalogue called search would live in src/catalogue/search.rs, declared with mod search; in catalogue.rs.
Privacy rules:
- Every item (function, struct, module, constant) is private by default: usable only inside its own module and that module's children.
pubmakes it visible to the parent and beyond.- A
pub structstill has private fields unless each field is markedpub. Apub enummakes all its variants public.
Paths name items: crate::catalogue::Book starts from the crate root, super:: goes to the parent module, self:: means the current one.
use creates a shortcut:
use crate::catalogue::Book;
use std::collections::{HashMap, HashSet};
let book = Book::new("Night Garden", 288);The shortcut
When the compiler says an item "is private", walk the path from the caller to the item and check every link is pub: the module, the type, the function, and any field you touch.
Module
mod catalogue;main is the parent, so the module itself is reachable.
The trap is making every field pub to silence errors. A private field plus a method keeps other code from putting the value into an invalid state.
Drills
Answer fast — trust the rule.
With mod catalogue; in src/main.rs, where does Rust look for the module's code?
A function in catalogue has no pub. Who can call it?
pub struct Book { title: String }. Can main read book.title?
Inside catalogue::search, which path reaches Book defined in catalogue?
Remember
- Modules form a tree inside a crate;
mod name;loadsname.rs. - Everything is private until
pub; a public struct's fields still need their ownpub. - When "is private" appears, check every link in the path; use methods instead of
pubfields.
