TExcelTAD
Home › Rust › Rust Modules & Cargo

Rust Modules & Cargo

As a program grows, keeping everything in one long main.rs becomes painful. Rust gives you two tools for organising code: modules, which group related items inside a crate, and Cargo, the build tool and package manager that manages whole projects and their dependencies.

Crates, packages and modules

Term Meaning
Crate One compilation unit: a binary (has main) or a library
Package A folder with a Cargo.toml that builds one or more crates
Module A named namespace inside a crate, declared with mod
Path The address of an item, e.g. shop::pricing::discount

Declaring a module

A module is declared with mod name { ... }. Everything inside is private by default; mark items with pub to make them visible outside the module. You reach items through a path with ::.

rust · try it yourself
mod greetings {
    pub fn morning(name: &str) -> String {
        format!("Good morning, {}!", name)
    }

    pub fn evening(name: &str) -> String {
        format!("Good evening, {}. {}", name, sign_off())
    }

    fn sign_off() -> &'static str {
        "Sleep well."
    }
}

fn main() {
    println!("{}", greetings::morning("Ada"));
    println!("{}", greetings::evening("Linus"));
    // greetings::sign_off(); // error: function `sign_off` is private
}
Good morning, Ada!
Good evening, Linus. Sleep well.

sign_off is a private helper: code inside greetings can call it, but main cannot. This lets a module hide its implementation details and expose only a small, tidy public API.

Nested modules, use, self and super

Modules can contain other modules. Long paths get tiresome, so the use keyword brings a name into scope. Inside a module, self means "this module" and super means "the parent module".

rust · try it yourself
mod shop {
    pub const CURRENCY: &str = "EUR";

    pub mod pricing {
        pub fn with_discount(price: f64, percent: f64) -> f64 {
            price * (1.0 - percent / 100.0)
        }

        pub fn label(price: f64) -> String {
            format!("{:.2} {}", price, super::CURRENCY)
        }
    }

    pub mod stock {
        pub fn is_low(count: u32) -> bool {
            count < 5
        }
    }
}

use shop::pricing::{label, with_discount};
use shop::stock;

fn main() {
    let price = with_discount(80.0, 25.0);
    println!("Sale price: {}", label(price));
    println!("Only 3 left? low stock = {}", stock::is_low(3));
    println!("Full path works too: {}", shop::pricing::label(10.0));
}
Sale price: 60.00 EUR
Only 3 left? low stock = true
Full path works too: 10.00 EUR

Tip: A common style is to use the parent module of a function (use shop::stock; then stock::is_low(...)) so it stays clear where the function lives.

Structs and enums in modules

Privacy works field by field for structs. A pub struct with private fields can only be built through a public constructor — a handy way to enforce rules. Enum variants, on the other hand, are all public if the enum is public.

rust · try it yourself
mod bank {
    pub struct Account {
        pub owner: String,
        balance: u64,
    }

    impl Account {
        pub fn open(owner: &str) -> Account {
            Account { owner: owner.to_string(), balance: 0 }
        }

        pub fn deposit(&mut self, amount: u64) {
            self.balance += amount;
        }

        pub fn balance(&self) -> u64 {
            self.balance
        }
    }
}

fn main() {
    let mut acc = bank::Account::open("Grace");
    acc.deposit(150);
    acc.deposit(50);
    println!("{} has {} coins", acc.owner, acc.balance());
    // acc.balance = 1_000_000; // error: field `balance` is private
}
Grace has 200 coins

Splitting modules into files

In a real project each module usually lives in its own file. Writing mod pricing; (with a semicolon instead of a block) tells the compiler to load the module body from a file:

my_shop/
├── Cargo.toml
└── src/
    ├── main.rs        // mod pricing; mod stock;
    ├── pricing.rs     // contents of the pricing module
    └── stock/
        ├── mod.rs     // or stock.rs next to a stock/ folder
        └── alerts.rs  // a sub-module: stock::alerts
rust
// src/main.rs
mod pricing;
mod stock;

fn main() {
    println!("{}", pricing::label(9.5));
}
rust
// src/pricing.rs
pub fn label(price: f64) -> String {
    format!("{:.2} EUR", price)
}

Cargo

Cargo creates projects, builds them, runs tests and downloads libraries (called crates) from crates.io.

bash
cargo new my_shop      # create a new binary project
cd my_shop
cargo run              # build and run
cargo build --release  # optimised build in target/release
cargo test             # run the tests
cargo add serde        # add a dependency to Cargo.toml

The project is described in Cargo.toml:

toml
[package]
name = "my_shop"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = "1.0"
Command What it does
cargo new Creates a project with Cargo.toml and src/main.rs
cargo check Type-checks quickly without producing a binary
cargo run Compiles and runs the program
cargo fmt Formats code in the standard style
cargo clippy Runs extra lints with helpful suggestions

Note: The playgrounds on this site compile a single file, so they cannot use external crates. Inline mod blocks work fine, though.

Test yourself

What is the default visibility of a function declared inside a module?

  1. Public
  2. Private
  3. Public within the crate
  4. Depends on the file name

Inside a nested module, what does super:: refer to?

  1. The crate root
  2. The current module
  3. The parent module
  4. The standard library

Which Cargo command creates a new project?

  1. cargo init-project
  2. cargo start
  3. cargo new
  4. cargo create