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.
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 privateuse: 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.
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.