Modules, Paths and Privacy
Modules organize names within a crate. Visibility rules determine which names other modules may use, and use introduces a path into scope under a local name.
Trace visible names through modules, paths and privacy boundaries.
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);