thecodex.expert · The Codex Family of Knowledge
Rust

Modules and Crates

Everything in Rust is private by default, at every level — a function, a struct field, even a whole module must be explicitly marked pub to be visible outside its own module.

Rust 1.96 Private by default Last verified:
Canonical Definition

A crate is the smallest amount of code the Rust compiler considers at one time — either a binary (with a main function) or a library. Within a crate, mod declares a module to organize related code, and every item (function, struct, module) is private to its parent module by default; pub explicitly opts an item into visibility outside that module. use brings a path into scope so it doesn't need to be fully qualified every time it's referenced.

Declaring modules and privacy

Without pub, an item is only reachable from within its own module and its descendants — a caller outside gets a compile error, not a runtime surprise.

Rustlib.rs
mod kitchen {
    pub fn cook() {          // pub: visible outside this module
        season();              // private fns ARE visible to code inside their own module
    }

    fn season() {             // private: only usable inside `kitchen`
        println!("seasoning");
    }
}

kitchen::cook();               // fine — cook is pub
// kitchen::season();          // COMPILE ERROR: season is private

use: bringing paths into scope

Without use, every reference to an item needs its full module path; use imports a shorter name into the current scope, similar in spirit to an import statement in other languages.

Rustuse_example.rs
use std::collections::HashMap;   // now HashMap works without the full path

let mut map = HashMap::new();     // instead of std::collections::HashMap::new()

Crates: binaries, libraries, and Cargo workspaces

A binary crate has a main.rs with a main function and compiles to an executable; a library crate has a lib.rs and compiles to code other crates can depend on. A Cargo workspace groups several related crates that share one Cargo.lock and target directory, common in larger projects split into multiple packages.

Sources

1
The Rust Project. The Rust Programming Language, "Managing Growing Projects with Packages, Crates, and Modules", doc.rust-lang.org/book/ch07.