Modules & Cargo — Rust

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…

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:

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.

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

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:

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:

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

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:

  1. Make an account (you log in through GitHub).
  2. Run cargo login with a token (a secret code for logging in) from the site.
  3. Fill in description (a short description) and license (the licence, the rules for using the code) under [package].
  4. 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?

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.

What you will learn