Crates packages and modules
Quick answer
A Cargo package is a project described by Cargo.toml. A crate is a compilation unit, and a module organizes names inside a crate. These boundaries help you divide a program without exposing every implementation detail.
Names and compilation boundaries
A package can contain one library crate and multiple binary crates. src/lib.rs and src/main.rs are conventional crate roots. mod declares a module; use introduces a shorter path in scope, not a new module. A binary may use its package's library by crate name.
mod prices { pub fn total(n: u32) -> u32 { n * 5 } }fn main() { println!("{}", prices::total(3)); }Expected stdout (not executed):
15The module groups pricing code within the same crate.
cargo new lesson_modulescd lesson_modulescargo metadata --no-deps --format-version 1Manual terminal step; not executed. Expected behavior (environment dependent):
A new package in an unused directory; metadata describes its target.Run in a disposable parent directory with an unused name. The JSON describes the binary target.
Common mistake
A package and a crate are not interchangeable terms.
Try it yourself
Add an inline module with a public function that calculates a shipping fee.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Crates packages and modules — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
One package has a library and two executable targets. How many crates are these targets?
Crates packages and modules — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust mod prices { pub fn total(n: u32) -> u32 { n * 5 } } fn main() { println!("{}", prices::total(3)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Crates packages and modules — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```bash cargo new lesson_modules cd lesson_modules cargo metadata --no-deps --format-version 1 ``` Which outcome or interpretation best matches this example?