Our cashier program already has a price function, an order struct and an error of its own, and all of it is piled into one main.rs. The longer the file gets, the harder it is to find things in it. Rust has two tools for organizing this. A module splits code into named parts. Each part has contents that are private (only for that part itself) and contents that are opened to other parts. Cargo, which you know from the first lesson, is the tool that compiles, runs and tests your project and fetches libraries for it.
As Rusdi's Pancake Stall gets busier, it is split into rooms too: the kitchen, the cashier, the storeroom. Each room has things only for the people inside it, like the secret recipe in the kitchen, and a service window for the other rooms. In code:
- Each room is one module, and the floor plan of all the rooms is the module tree (a tree of modules: modules that hold other modules).
- The things behind the door are the private contents, and the window is
pub, the mark that those contents are opened to other modules. - The stall's business licence plus its list of suppliers is
Cargo.toml: your project's identity and the list of libraries it uses. - The market where all the suppliers sell is crates.io, the site where Rust libraries are shared.
mod: rooms inside one file
This program makes a module menu inside main.rs, holding the function price (the pub in front of it is covered in the next section):
mod menu {
pub fn price(name: &str) -> Option<u32> {
match name {
"sweet pancake" => Some(32),
"egg pancake" => Some(38),
"iced tea" | "iced orange" => Some(5),
_ => None,
}
}
}
fn main() {
println!("{:?}", menu::price("iced tea"));
}
It prints Some(5). mod menu { ... } makes a module named menu. Its contents are called through the path (the address in the module tree) menu::price, with :: as in String::from. The whole program is a tree of modules, and its root is main.rs. One cargo new makes one crate: one project that is compiled together. A library from crates.io is a crate too.
pub: everything is private until opened
Now add the function secret_recipe inside the mod menu { ... } above, next to pub fn price, but without pub:
fn secret_recipe() -> String {
String::from("duck eggs, spring onion, Rusdi's spice mix")
}
Then main calls println!("{}", menu::secret_recipe());. Does it compile, since it's all in one file? Guess before you look at the result:
error[E0603]: function `secret_recipe` is private
--> src/main.rs:18:26
|
18 | println!("{}", menu::secret_recipe());
| ^^^^^^^^^^^^^ private function
|
note: the function `secret_recipe` is defined here
--> src/main.rs:11:5
|
11 | fn secret_recipe() -> String {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It doesn't compile, even in one file. In Rust every item is private by default. Functions, structs, fields and modules are only visible in the module they're written in, plus the modules inside it. What decides is the module, not the file.
pubopens an item to all code that can see its module. That is whypub fn pricemay be called frommain.pub(crate)opens an item to this crate only. The difference frompubshows when the stall's code becomes a library used by other crates: apub(crate)item stays closed to those other crates.pub structdoesn't open its fields automatically. For example,mod cashierholdspub struct Order { pub customer: String, items: Vec<u32> }: the fieldcustomeris markedpub, butitemsisn't. Ifmainwritescashier::Order { customer: ..., items: vec![38] }, the compiler refuses with E0451field `items` of struct `Order` is private. So anOrderis made through apub fn new(...)inside the module, likeOrder::newin the struct lesson. That way, the fielditemscan only change through its methods.
Modules in their own files
When modules grow, put each module in its own file. The folders of the project stall become:
stall/
├── Cargo.toml
└── src/
├── main.rs
├── menu.rs
└── cashier/
├── mod.rs
└── receipt.rs
The first comment line in each code file below names that file, and the last part is the output of cargo run:
// src/main.rs
mod cashier;
mod menu;
fn main() {
let order = ["sweet pancake", "sweet pancake", "egg pancake"];
println!("Total: {}", cashier::total(&order));
cashier::receipt::print("Sari", &order);
}
// src/menu.rs
/// The price of one menu item, or `None` if it isn't on the menu.
pub fn price(name: &str) -> Option<u32> {
match name {
"sweet pancake" => Some(32),
"egg pancake" => Some(38),
"iced tea" | "iced orange" => Some(5),
_ => None,
}
}
// src/cashier/mod.rs
pub mod receipt;
use crate::menu;
/// The total price of every menu item in the order. An unknown item counts as 0.
pub fn total(order: &[&str]) -> u32 {
order.iter().map(|m| menu::price(m).unwrap_or(0)).sum()
}
// src/cashier/receipt.rs
pub fn print(customer: &str, order: &[&str]) {
println!("{} pays {}", customer, super::total(order));
}
$ cargo run
Compiling stall v0.1.0 (/home/you/stall)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.82s
Running `target/debug/stall`
Total: 102
Sari pays 102
mod menu;with a semicolon means "this module's contents are in another file". The compiler (which Cargo runs) looks for it insrc/menu.rsorsrc/menu/mod.rs. Each module is declared (named withmod) once, in its parent module, which is the module that holds it. The file's contents are not wrapped inmod menu { }again.cashierhas a child module,receipt, socashierneeds a folder.pub mod receipt;incashier/mod.rsmakesreceiptvisible from outsidecashier, somaincan callcashier::receipt::print. The file forcashieritself can be written in two ways:src/cashier/mod.rs(the older way, still common) orsrc/cashier.rsnext to thesrc/cashier/folder (the way recommended since the 2018 edition). Pick one. If both exist, the compiler refuses with E0761file for module `cashier` found at both "src/cashier.rs" and "src/cashier/mod.rs".- If the file can't be found, the compiler refuses with E0583
file not found for module `menu`, with the advicecreate file "src/menu.rs" or "src/menu/mod.rs".
use and paths: crate::, super::, self::
Inside cashier, the name menu isn't known automatically, because menu is a sibling of cashier (both are children of main.rs), not its child. The path can be written three ways:
crate::starts at the crate root (main.rs):crate::menu::price. It's an absolute path: it is written the same from any module.super::starts at the parent module: fromcashier/receipt.rs,super::totaliscashier'stotal. Fromcashier,super::menu::pricealso reachesmenu.self::starts at this module itself: fromcashier,self::receipt::print. It is rarely needed, since a path with no prefix already starts at this module.
use crate::menu; in cashier/mod.rs makes the name menu usable in the module cashier, so menu::price is enough. Without that use, menu::price(m) in cashier is refused with E0433 cannot find module or crate `menu` in this scope, and the compiler suggests use crate::menu;. The use std::collections::HashMap; from the HashMap lesson does the same thing for the standard library.
Cargo.toml and dependencies
cargo new stall makes a stall folder with Cargo.toml, src/main.rs and .gitignore (the list of files that git ignores; git is a program that records the history of your code). Cargo.toml is the project's manifest, the file that describes the project: the package's identity (the name and version of your project), its edition and its list of dependencies (other libraries your project uses).
[package]
name = "stall"
version = "0.1.0"
edition = "2024"
[dependencies]
chrono = "0.4.45"
The line chrono = "0.4.45" is written by the command cargo add chrono. chrono is a crate for dates and times. Cargo looks up its newest version on crates.io (Adding chrono v0.4.45 to dependencies), then locks the versions of every package it needs (Locking 37 packages). After that, chrono can be used in receipt.rs:
use chrono::Local;
pub fn print(customer: &str, order: &[&str]) {
let date = Local::now().format("%d-%m-%Y");
println!("{} | {} pays {}", date, customer, super::total(order));
}
Local::now() takes the current date and time, and format("%d-%m-%Y") writes it as day-month-year. cargo run now prints 12-10-2026 | Sari pays 102, with the date of the day you run it. Things to remember:
"0.4.45"means "0.4.45 or a newer version that is still compatible", such as 0.4.46, but not 0.5.0.- The exact versions actually used, including the 36 other packages chrono needs, are recorded in
Cargo.lock. For an application, keep this file in git so the build is the same on every computer. - crates.io is the official registry (storage place) of Rust crates, like npm for JavaScript. A crate used only for testing goes under
[dev-dependencies].
Everyday cargo commands
These are the results of two commands, cargo check and cargo build --release:
$ cargo check
Checking stall v0.1.0 (/home/you/stall)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s
$ cargo build --release
Compiling stall v0.1.0 (/home/you/stall)
Finished `release` profile [optimized] target(s) in 0.78s
cargo buildcompiles intotarget/debug/stall, andcargo runcompiles (if anything changed) and then runs it.cargo checkonly checks the types and borrows, without making a program file. It's much faster, so it's handy to run over and over while writing code.cargo build --releasecompiles with optimisations intotarget/release/stall: it takes longer to compile, but the program runs much faster. This file is what goes on the cashier's computer.cargo docmakes documentation as HTML pages from///comments (documentation comments), like those inmenu.rsandcashier/mod.rs. The result is intarget/doc/stall/index.html. Add--opento open it right away.
A test is code that checks whether your code gives the right results. These tests are written at the bottom of menu.rs, in the same file as the price function they check:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn price_egg_pancake() {
assert_eq!(price("egg pancake"), Some(38));
}
#[test]
fn no_coffee() {
assert_eq!(price("coffee"), None);
}
}
$ cargo test
Compiling stall v0.1.0 (/home/you/stall)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s
Running unittests src/main.rs (target/debug/deps/stall-9c40172ca2dacfc5)
running 2 tests
test menu::tests::no_coffee ... ok
test menu::tests::price_egg_pancake ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
#[cfg(test)] makes the tests module compile only for cargo test. use super::*; brings everything from its parent module, menu, including price, into tests. Each function marked #[test] is one test, and assert_eq! checks that its two values are equal. The tests run at the same time, so the order of the result lines can differ from run to run.
There are two more tools. cargo clippy looks for code that is correct but could be written better. For example, if total starts with if order.len() == 0 { return 0; }, clippy gives this warning:
warning: length comparison to zero
--> src/cashier/mod.rs:7:8
|
7 | if order.len() == 0 {
| ^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `order.is_empty()`
cargo fmt tidies the spacing and indentation (the space from the left edge) of every file into the standard Rust style. For example, cargo fmt changes pub fn print(customer:&str,order:&[&str]){ into pub fn print(customer: &str, order: &[&str]) {. cargo fmt --check only shows the difference, without changing the files.
📌 Workspaces and publishing a crate
If the stall's code grows into several crates, put those crates together in a workspace (one folder for several crates). For example, those crates could be the cashier app, and a menu library that the delivery app also uses. To do this, write one Cargo.toml in the top folder, holding [workspace] with members = ["cashier", "menu"]. All members share one Cargo.lock and one target/ folder. So a shared dependency is compiled once, and cargo test in the top folder tests them all.
To publish a crate on crates.io:
- Make an account (you log in through GitHub).
- Run
cargo loginwith a token (a secret code for logging in) from the site. - Fill in
description(a short description) andlicense(the licence, the rules for using the code) under[package]. - Run
cargo publish.
A published version can't be overwritten. If something is wrong, publish a new version, and mark the old one with cargo yank so new projects don't use it. The full guide is in The Cargo Book, chapter "Publishing on crates.io".
⚠️ Why can't anything outside see inside your module?
- Forgetting
pub. E0603function `...` is private, even in one file. Open it withpub, orpub(crate). - A
pub structwith private fields. E0451 when filling the field from outside the module. Provide apub fn new(...), or mark the fieldpub. - A module file that is missing or doubled. E0583 when
src/menu.rsdoesn't exist, and E0761 when bothsrc/cashier.rsandsrc/cashier/mod.rsexist. - A sibling's path without
crate::.menu::priceinsidecashier: E0433. Writecrate::menu::price,super::menu::price, oruse crate::menu;.
TL;DR: A module is a named part of your code. mod menu { ... }, or mod menu; with its contents in src/menu.rs, makes a module, and its contents are called through the path (the address), such as menu::price. Every item (function, struct, module) is private until given pub (E0603). pub(crate) opens it to this crate only (one project from cargo new), and struct fields stay private unless marked pub (E0451). A module with child modules uses src/cashier/mod.rs or src/cashier.rs, never both (E0761). Paths start at the root (main.rs) with crate::, at the parent module with super::, at this module with self::, and use shortens them. Cargo.toml is the manifest (the file that describes the project): [package] (name, version, edition 2024) and [dependencies] (the libraries it uses; cargo add chrono writes chrono = "0.4.45"). The exact versions are recorded in Cargo.lock. Everyday commands: cargo build, run, check (only checks, fastest), test, build --release, doc, clippy and fmt.
⚡ mod: named rooms
Write:
mod menu {
pub fn price(name: &str) -> Option<u32> {
match name {
"iced tea" | "iced orange" => Some(5),
_ => None,
}
}
}
fn main() {
println!("{:?}", menu::price("iced tea"));
}
Meaning: mod menu { ... } makes a module, a named part of your code, like one room in the stall. Its contents are called through the path (their address) menu::price, and pub lets price be called from outside menu. One cargo new is one crate: all the modules of that project, starting from main.rs.
⚡ Private until opened
Guess first: fn secret_recipe() is written without pub in mod menu, in the same file. Does menu::secret_recipe() from main compile?
No: E0603 function `secret_recipe` is private. What decides who may call it is the module, not the file.
Meaning: Every item (function, struct, module) is private by default: it is only visible inside its module. pub opens it, and pub(crate) opens it to this crate only.
⚡ Cargo.toml, the project's manifest
Write:
[package]
name = "stall"
version = "0.1.0"
edition = "2024"
[dependencies]
chrono = "0.4.45"
Meaning: Cargo.toml is the project's manifest (the file that describes it). It holds the package's identity (name and version), its edition (the version of Rust's language rules) and its list of dependencies: the libraries from crates.io (the site where Rust libraries are shared) that your project uses, here chrono for dates and times. cargo add chrono writes the dependency line, and the exact versions used are recorded in Cargo.lock.