Skip to content
LumenaryAcademy
Professional 70 min

Tooling, ecosystem and a complete project

Cargo, crates.io, rustfmt and Clippy as professionals use them, and a small program built from everything in the course.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From a file to a project

Everything so far fits in one file. Real Rust work happens in projects with dozens of modules, a few hundred dependencies (most of them indirect), automated formatting and linting, documentation, tests and continuous integration. Part of what draws people to Rust is that this machinery is standard: every Rust project uses Cargo, almost every one is formatted by rustfmt and checked by Clippy, and documentation for every public library is built the same way and published in the same place. Moving between Rust codebases at different companies feels unusually familiar.

This lesson walks through that machinery as a professional uses it day to day, then puts the whole course together in a complete small program: a tool that splits shared expenses among friends and works out who should pay whom. It is about 240 lines, all standard library, and every line uses something from an earlier lesson.

DefinitionsH

Modules, crates and visibility

Definition— module

A module is a named scope for items (functions, types, traits, constants, other modules). mod money { ... } defines one inline; mod money; tells the compiler to load it from src/money.rs (or src/money/mod.rs). Items are private to their module by default; pub makes an item visible to the parent module and beyond, pub(crate) to the whole crate only. use brings a path into scope, and paths start from the crate root with crate::, from the parent with super::, or from an external crate's name.

A Cargo package usually contains a library crate (src/lib.rs), which holds the logic, and a thin binary crate (src/main.rs), which parses arguments, calls the library and reports errors. Splitting them this way means integration tests and other programs can use the library, and the binary stays small enough to read at a glance. A typical layout:

text
splitwise-lite/
├── Cargo.toml
├── Cargo.lock
├── src/
│   ├── main.rs        # the binary: arguments, output, exit code
│   ├── lib.rs         # pub mod money; pub mod ledger;
│   ├── money.rs
│   └── ledger.rs
└── tests/
    └── settle.rs      # integration tests, using only the public API

Privacy is enforced at module boundaries, not at type boundaries, which is how Rust does encapsulation without classes: a struct's private fields can be touched by any code in the same module and by no code outside it. A good public API exposes a few types and functions with pub and hides the rest; the compiler then guarantees that callers cannot depend on your internals, so you can change them freely.

Worked examplesH

Cargo in practice

A realistic manifest for a small command-line tool:

toml
[package]
name = "splitwise-lite"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"          # the oldest compiler this crate supports

[dependencies]
clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"

[dev-dependencies]             # only for tests and examples
proptest = "1"

[lints.clippy]
unwrap_used = "warn"

[profile.release]
lto = true                     # slower build, smaller and faster binary

Version requirements follow semantic versioning. serde = "1" means "any version from 1.0.0 up to, but not including, 2.0.0", on the understanding that a library only breaks its API when its major version changes (for versions below 1.0, a change in the minor number counts as breaking). The first build resolves these ranges to exact versions and records them in Cargo.lock, so every later build, on every machine, uses exactly the same code until you run cargo update. Commit the lock file for applications, so builds are reproducible. Features are optional parts of a crate, switched on per dependency (features = ["derive"]), which keeps compile times and binary sizes down.

The commands you will use every week, beyond new, check, build, run and test:

CommandWhat it does
cargo add clap --features deriveadds a dependency to Cargo.toml
cargo fmtformats every file with rustfmt
cargo clippyruns Clippy's lints (several hundred of them)
cargo doc --openbuilds HTML documentation for your crate and all dependencies
cargo treeshows the dependency graph, and why each crate is there
cargo updatemoves Cargo.lock to the newest compatible versions
cargo install ripgrepbuilds and installs a binary from crates.io
cargo publishuploads a library to crates.io

Larger projects group several packages into a workspace, with a top-level Cargo.toml listing the members; they share one lock file and one target directory. Splitting a big crate into several also speeds up builds, because the compiler can work on crates in parallel and recompile only what changed.

ExplanationH

The everyday toolchain

rustfmt settles every argument about style: there is one standard layout, and teams run cargo fmt --check in CI to keep it. (All the programs in this course are formatted by it, which is why long struct literals spread over several lines.) Configuration is possible but rare.

Clippy is the linter. Its default lints catch real bugs (== between floats where you meant a tolerance, an iterator chain whose result is ignored), unidiomatic code (a manual loop that is just .find(), &String parameters) and performance traps (needless clones and allocations). When the example programs in this course were checked, Clippy suggested several improvements: is_multiple_of instead of % d == 0, sort_by_key with Reverse instead of a hand-written comparison, an array instead of a needless vec!. Many teams run it with -D warnings in CI so that no warning can be merged, and turn on extra groups (clippy::pedantic) selectively.

rust-analyzer is the language server behind Rust support in VS Code, Zed, Neovim, Helix, Emacs and others: completion, go-to-definition, inline types, rename, and quick fixes that apply the compiler's own suggestions. (JetBrains' RustRover has its own engine.)

rustdoc turns /// comments into documentation; Markdown, links between items ([Cents::split]) and code examples are all supported, and the examples run as doc tests. Every crate published to crates.io gets its documentation built and hosted on docs.rs, so the documentation of any library you use is one click away and always matches the version you have.

Supply-chain tools matter because a typical project pulls in many indirect dependencies. cargo-audit checks your lock file against the RustSec advisory database of known vulnerabilities; cargo-deny also enforces licence and source policies; cargo-vet records which dependencies a human has reviewed. Miri (lesson 9) checks unsafe code; cargo-semver-checks warns library authors before they publish an accidental breaking change.

A minimal but realistic CI pipeline runs cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test and cargo audit on every pull request.

Crates you will meet everywhere

The standard library is deliberately small; the ecosystem fills in the rest. A handful of crates are so common that you can treat them as part of the language's working vocabulary:

NeedCrates
serialisation (JSON, TOML, YAML, binary formats)serde, serde_json, toml
command-line argumentsclap
errorsthiserror (libraries), anyhow (applications)
async runtime, HTTPtokio, reqwest (client), axum (server)
data parallelismrayon
logging and tracingtracing, log
regular expressionsregex
databasessqlx, diesel, rusqlite
testing and benchmarkingproptest, insta, criterion

Before adding a dependency, experienced engineers check how widely it is used, whether it is maintained, what it pulls in (cargo tree), and whether a few lines of your own code would do. The splitter below deliberately uses none.

Worked examplesH

Shaping a command-line program

The professional shape of a command-line tool is: main collects the arguments and the environment, calls ordinary functions that return Results, prints and exits. The functions in the middle never touch the process, so tests can call them directly. Here is that shape, with arguments parsed by hand (in real projects, clap generates this from a struct with #[derive(Parser)]):

rust
use std::process::ExitCode;

#[derive(Debug, PartialEq)]
struct Options {
    verbose: bool,
    limit: usize,
    files: Vec<String>,
}

/// Turns command-line arguments into Options. Kept separate from `main`
/// so that it can be tested without starting a process.
fn parse_args<S: AsRef<str>>(args: &[S]) -> Result<Options, String> {
    let mut opts = Options {
        verbose: false,
        limit: 10,
        files: Vec::new(),
    };
    let mut iter = args.iter().map(AsRef::as_ref);
    while let Some(arg) = iter.next() {
        match arg {
            "-v" | "--verbose" => opts.verbose = true,
            "--limit" => {
                let value = iter.next().ok_or("--limit needs a number")?;
                opts.limit = value
                    .parse()
                    .map_err(|_| format!("bad --limit {value:?}"))?;
            }
            flag if flag.starts_with('-') => return Err(format!("unknown option {flag}")),
            file => opts.files.push(file.to_string()),
        }
    }
    if opts.files.is_empty() {
        return Err(String::from("no input files"));
    }
    Ok(opts)
}

fn main() -> ExitCode {
    // The real arguments (none when this lesson's checker runs it).
    let real: Vec<String> = std::env::args().skip(1).collect();
    println!("real arguments: {real:?}");

    // The same function, exercised the way a test would.
    let tries: [&[&str]; 4] = [
        &["notes.txt"],
        &["-v", "--limit", "5", "a.txt", "b.txt"],
        &["--limit", "many", "a.txt"],
        &["--colour", "a.txt"],
    ];
    for args in tries {
        match parse_args(args) {
            Ok(o) => println!("{args:?} -> ok: {o:?}"),
            // A real tool would report errors with eprintln!, to standard error.
            Err(e) => println!("{args:?} -> error: {e}"),
        }
    }
    ExitCode::SUCCESS
}
text
real arguments: []
["notes.txt"] -> ok: Options { verbose: false, limit: 10, files: ["notes.txt"] }
["-v", "--limit", "5", "a.txt", "b.txt"] -> ok: Options { verbose: true, limit: 5, files: ["a.txt", "b.txt"] }
["--limit", "many", "a.txt"] -> error: bad --limit "many"
["--colour", "a.txt"] -> error: unknown option --colour

The generic parameter S: AsRef<str> lets parse_args accept a slice of Strings (real arguments) or of &strs (tests) alike. main returns std::process::ExitCode, so it can choose a failure code without panicking; a real tool would return ExitCode::FAILURE when parsing fails.

Worked examplesH

The project: splitting shared expenses

Four friends on a weekend trip take turns paying: one pays for a boat, another for lunch for two, and so on. At the end, who owes whom? The program reads a small ledger in a forgiving text format, computes each person's net balance (what they paid minus their share of everything), and proposes payments that bring everyone to zero.

rust
//! splitwise-lite: who owes whom after a shared trip.
//! Reads a small ledger, computes each person's balance in whole cents,
//! and suggests a short list of payments that settles everything.

mod money {
    use std::fmt;
    use std::ops::{AddAssign, Neg};

    /// An amount of money in cents. Integers, never floats, for money.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
    pub struct Cents(pub i64);

    impl Cents {
        /// Parses "12", "12.5" or "12.50" into cents. No signs, at most two decimals.
        pub fn parse(text: &str) -> Option<Cents> {
            let (whole, frac) = text.split_once('.').unwrap_or((text, ""));
            let digits = whole
                .bytes()
                .chain(frac.bytes())
                .all(|b| b.is_ascii_digit());
            if !digits || whole.is_empty() || frac.len() > 2 {
                return None;
            }
            let whole: i64 = whole.parse().ok()?;
            let frac: i64 = format!("{frac:0<2}").parse().ok()?;
            Some(Cents(whole * 100 + frac))
        }

        /// Splits into `n` shares that differ by at most one cent and add up exactly.
        pub fn split(self, n: usize) -> Vec<Cents> {
            let n = i64::try_from(n).expect("share count fits in an i64");
            let (base, extra) = (self.0 / n, self.0 % n);
            (0..n).map(|i| Cents(base + i64::from(i < extra))).collect()
        }
    }

    impl fmt::Display for Cents {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let sign = if self.0 < 0 { "-" } else { "" };
            let text = format!("{sign}{}.{:02}", self.0.abs() / 100, self.0.abs() % 100);
            f.pad(&text) // pad, unlike write!, honours widths such as {:>8}
        }
    }

    impl Neg for Cents {
        type Output = Cents;
        fn neg(self) -> Cents {
            Cents(-self.0)
        }
    }

    impl AddAssign for Cents {
        fn add_assign(&mut self, o: Cents) {
            self.0 += o.0;
        }
    }
}

mod ledger {
    use crate::money::Cents;
    use std::collections::BTreeMap;
    use std::fmt;

    pub struct Expense {
        pub payer: String,
        pub amount: Cents,
        pub what: String,
        pub shared_by: Vec<String>,
    }

    /// A problem in the input, with the line where it was found.
    #[derive(Debug)]
    pub struct ParseError {
        pub line: usize,
        pub problem: String,
    }

    impl fmt::Display for ParseError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "line {}: {}", self.line, self.problem)
        }
    }

    impl std::error::Error for ParseError {}

    fn error(line: usize, problem: impl Into<String>) -> ParseError {
        let problem = problem.into();
        ParseError { line, problem }
    }

    /// Reads "people: A B C", then lines like "A paid 12.50 for taxi, split A B" (or "split all").
    pub fn parse(text: &str) -> Result<(Vec<String>, Vec<Expense>), ParseError> {
        let mut lines = text
            .lines()
            .enumerate()
            .map(|(i, l)| (i + 1, l.trim()))
            .filter(|(_, l)| !l.is_empty() && !l.starts_with('#'));

        let (n, first) = lines
            .next()
            .ok_or_else(|| error(1, "the ledger is empty"))?;
        let names = first
            .strip_prefix("people:")
            .ok_or_else(|| error(n, "expected `people:` and a list of names"))?;
        let people: Vec<String> = names.split_whitespace().map(String::from).collect();
        let known = |line: usize, name: &str| {
            if people.iter().any(|p| p == name) {
                Ok(name.to_string())
            } else {
                Err(error(line, format!("who is {name}?")))
            }
        };

        let mut expenses = Vec::new();
        for (line, text) in lines {
            let shape = || error(line, "expected `NAME paid AMOUNT for WHAT, split NAMES`");
            let (head, split) = text.split_once(", split ").ok_or_else(shape)?;
            let (payer, rest) = head.split_once(" paid ").ok_or_else(shape)?;
            let (amount, what) = rest.split_once(" for ").ok_or_else(shape)?;
            let amount = Cents::parse(amount)
                .ok_or_else(|| error(line, format!("{amount:?} is not an amount")))?;
            let shared_by = match split {
                "all" => people.clone(),
                names => names
                    .split_whitespace()
                    .map(|name| known(line, name))
                    .collect::<Result<_, _>>()?,
            };
            let payer = known(line, payer)?;
            let what = what.to_string();
            expenses.push(Expense {
                payer,
                amount,
                what,
                shared_by,
            });
        }
        Ok((people, expenses))
    }

    /// Net balance per person: positive means they are owed money.
    pub fn balances(people: &[String], expenses: &[Expense]) -> BTreeMap<String, Cents> {
        let mut net: BTreeMap<String, Cents> =
            people.iter().map(|p| (p.clone(), Cents(0))).collect();
        for e in expenses {
            *net.entry(e.payer.clone()).or_default() += e.amount;
            let shares = e.amount.split(e.shared_by.len());
            for (person, share) in e.shared_by.iter().zip(shares) {
                *net.entry(person.clone()).or_default() += -share;
            }
        }
        net
    }

    /// Greedy settlement: the biggest debtor pays the biggest creditor until all are even.
    pub fn settle(net: &BTreeMap<String, Cents>) -> Vec<(String, String, Cents)> {
        let mut owed: Vec<(String, Cents)> = net.iter().map(|(p, c)| (p.clone(), *c)).collect();
        let mut payments = Vec::new();
        loop {
            owed.sort_by_key(|(name, c)| (*c, name.clone()));
            let (debtor, debt) = owed.first().cloned().unwrap_or_default();
            let (creditor, credit) = owed.last().cloned().unwrap_or_default();
            if debt >= Cents(0) || credit <= Cents(0) {
                return payments;
            }
            let amount = (-debt).min(credit);
            payments.push((debtor, creditor, amount));
            let last = owed.len() - 1;
            owed[0].1 += amount;
            owed[last].1 += -amount;
        }
    }
}

use ledger::{balances, parse, settle};
use money::Cents;

const TRIP: &str = "
# A weekend in Zanzibar
people: Asha Ben Chidi Dara

Asha paid 120.00 for boat trip, split all
Ben paid 45.50 for lunch, split Asha Ben
Chidi paid 61 for spice farm tour, split all
Dara paid 18.25 for taxi, split Chidi Dara
";

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (people, expenses) = parse(TRIP)?;
    for e in &expenses {
        println!(
            "{} paid {} for {}, shared by {}",
            e.payer,
            e.amount,
            e.what,
            e.shared_by.len()
        );
    }

    let net = balances(&people, &expenses);
    for (person, amount) in &net {
        println!("  {person:<6} {amount:>8}");
    }

    let payments = settle(&net);
    for (from, to, amount) in &payments {
        println!("{from} pays {to} {amount}");
    }

    // Self-checks, as a test suite would run them.
    let total: i64 = net.values().map(|c| c.0).sum();
    assert_eq!(total, 0, "balances must sum to zero");
    let mut after = net.clone();
    for (from, to, amount) in &payments {
        *after.get_mut(from).unwrap() += *amount;
        *after.get_mut(to).unwrap() += -*amount;
    }
    assert!(
        after.values().all(|c| *c == Cents(0)),
        "payments must settle every balance"
    );
    assert_eq!(
        Cents(1000).split(3),
        vec![Cents(334), Cents(333), Cents(333)]
    );
    assert_eq!(Cents::parse("12.5"), Some(Cents(1250)));
    assert_eq!(Cents::parse("1.234"), None);
    assert_eq!(Cents::parse("-5"), None);

    let mistakes = [
        "people: Asha Ben\nAsha paid lots for dinner, split all",
        "people: Asha Ben\nAsha paid 9 for tea, split Asha Zawadi",
        "people: Asha Ben\nBen bought 9 of tea, split all",
    ];
    for text in mistakes {
        match parse(text) {
            Ok(_) => println!("accepted, but should not have been"),
            Err(e) => println!("rejected: {e}"),
        }
    }
    println!("all checks passed");
    Ok(())
}
text
Asha paid 120.00 for boat trip, shared by 4
Ben paid 45.50 for lunch, shared by 2
Chidi paid 61.00 for spice farm tour, shared by 4
Dara paid 18.25 for taxi, shared by 2
  Asha      52.00
  Ben      -22.50
  Chidi      6.62
  Dara     -36.12
Dara pays Asha 36.12
Ben pays Asha 15.88
Ben pays Chidi 6.62
rejected: line 2: "lots" is not an amount
rejected: line 2: who is Zawadi?
rejected: line 2: expected `NAME paid AMOUNT for WHAT, split NAMES`
all checks passed

A tour of the design, lesson by lesson:

  • Money is an integer newtype (lessons 2, 5). Floating-point numbers cannot represent most decimal fractions exactly (recall 0.1 + 0.2), so financial code counts in whole cents. Cents derives the comparison traits it needs, implements Display (with f.pad, so {:>8} alignment works), Neg and AddAssign (lesson 6), and nothing it doesn't need.
  • Splitting never loses a cent. 10.00 among three people becomes 3.34, 3.33 and 3.33: split gives the remainder cents to the first shares, one each, so the parts always add up to the whole. Integer division and remainder (lesson 2) do the work.
  • Modules draw the boundaries (this lesson). money knows nothing about people; ledger knows nothing about printing. Only items marked pub are visible to main.
  • Parsing returns Result (lesson 8). Each failure becomes a ParseError with a line number and a message a person can act on, and ? propagates the first one. ok_or_else takes a closure, so the error message is only built when something actually went wrong. Collecting the names into Result<_, _> stops at the first unknown name (lesson 7).
  • Closures capture context (lesson 7). known borrows the list of people, and shape captures the line number.
  • Collections fit their jobs (lesson 7). Balances live in a BTreeMap, so they print in a stable alphabetical order; the settlement works on a Vec that it re-sorts each round.
  • The checks at the end of main are the test suite (lesson 8): the balances sum to zero, the payments really settle everything, splitting and parsing behave at the edges, and bad input is rejected with useful messages. In a Cargo project they would be #[test] functions, plus a property-based test generating random ledgers.

The settlement rule is greedy: the person who owes most pays the person owed most, as much as possible, and repeat. Each payment settles at least one person, so there are at most n − 1 payments for n people. It does not always find the fewest possible payments; finding that minimum is NP-hard in general, because it contains subset-sum problems (Lumenary CS's lesson on hard problems explains what that means). For a group of friends, a simple greedy rule like this is more than good enough.

Extending it

Good next steps, each of which exercises a different part of the language: read the ledger from a file named on the command line (std::fs::read_to_string and ?); support currencies, with a Currency enum and conversion rates, refusing to add amounts in different currencies (make the type system enforce it); output JSON with serde; replace the main-based checks with #[test] functions and a proptest property ("for any ledger, the settlement zeroes every balance"); and split it into lib.rs and main.rs with clap for arguments.

Further reading

Where to go next

You now know the core of Rust and how it is used professionally. Some well-trodden paths onward:

  • Practise. Rustlings is a set of small exercises run from the terminal, maintained under the Rust project's GitHub organisation; Exercism's Rust track offers mentored exercises.
  • Read the official books for depth: the book itself, then the Cargo Book and the Reference, and when you are ready for unsafe code and its rules, the Rustonomicon. All are linked from rust-lang.org/learn.
  • Read real code. Popular, well-written crates are excellent teachers: ripgrep (a fast search tool), serde, tokio, clap. Their source is linked from crates.io and docs.rs.
  • Pick a domain. Web services (axum, sqlx), command-line tools (clap, ratatui), WebAssembly (wasm-bindgen), embedded systems (the Embedded Rust book, Embassy), games (Bevy), data engineering (Polars, Arrow, DataFusion).
  • Follow the language. The Rust blog announces every release; This Week in Rust collects news, articles and "good first issues" in open-source projects that welcome new contributors.
Optional Christian reflection · Rules that set you free

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Many people describe the first weeks of Rust as a struggle with a compiler that keeps saying no, and the months after as a surprising kind of freedom: once the rules are understood, they can refactor fearlessly, share data across threads without dread, and trust that whole classes of mistakes simply cannot happen. An old psalm says something similar about a much larger kind of law: "And I will walk at liberty: for I seek thy precepts" (Psalm 119:45, King James Version). Good limits, kept with understanding, can protect and even free rather than confine. Whatever you make of that, the craft lesson holds: constraints chosen well, and understood rather than merely obeyed, are what let people build things that last and that others can rely on.

Common misconceptionsH

Common misconceptions

Misconception

"Fewer dependencies is always better, so write everything yourself." Each dependency is code you trust and must keep updated, so be choosy. But a mature, widely used crate like serde or regex has had far more review, fuzzing and real-world use than a home-grown replacement will. The professional habit is deliberate choice, not avoidance.

Misconception

"Clippy warnings are just style opinions." Some are, and you can turn those off. Many point at real bugs or real performance problems, and the default set is chosen to have few false alarms. Read each one before silencing it, and silence it narrowly (#[allow(clippy::...)] on one item) with a comment saying why.

Misconception

"Cargo.lock is clutter." For an application it is what makes a build next year use the same dependency versions as today's tested build. Commit it. (Library authors often commit it too, for reproducible CI, even though users of the library resolve their own versions.)

Misconception

"pub on a struct makes its fields public." It makes the type nameable outside the module. Each field is private unless it is marked pub itself, which is how a type can be public while guaranteeing its own invariants.

Exercises

Exercises

1. Tooling, ecosystem and a complete project

CoreHuman

A Cargo.toml says regex = "1.10". Which version could Cargo choose when it first resolves dependencies?

Choose one

2. Tooling, ecosystem and a complete project

Warm-upHuman

Which pairings of job and tool are correct? Choose all that apply.

Choose all that apply

3. Tooling, ecosystem and a complete project

CoreComputational

Using the project's Cents type, what does println!("{} {} {}", Cents(-2250), Cents(5), Cents(100000)); print?

4. Tooling, ecosystem and a complete project

CoreComputational

Cents(100).split(6) divides one unit of currency into six shares. How many of the shares are 17 cents?

5. Tooling, ecosystem and a complete project

StretchComputational

Three friends have net balances A: +30.00, B: −10.00, C: −20.00. How many payments does the project's greedy settle produce?

6. Tooling, ecosystem and a complete project

CoreHuman

In module money, pub struct Wallet { owner: String, balance: Cents } is declared with no pub on the fields. What can code in main (outside the module) do?

Choose one

Further reading and resources