Skip to the workspace
Pebellslearn by building
Modules and Crates  ›  Lesson

Modules, Paths and Privacy

Code Organization & Namespacing 15 minModules 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.

rust / Modules, Paths and Privacy

Explore each scene at your own pace.

01 · The rule

The rule

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; use shortens 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() }   // private

A 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.
  • pub makes it visible to the parent and beyond.
  • A pub struct still has private fields unless each field is marked pub. A pub enum makes 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);
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.