Rust · Chapter 16 of 26

Modules and Cargo

By the end of this chapter you can split a crate into modules, one file each, decide what each module shows with pub and pub(crate), reach any item with use and a path, re-export the names callers should use, build a library with lib.rs as its root, add one of the lab's crates to Cargo.toml, and keep the code clean with cargo fmt, cargo clippy and doc comments. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Real programs
  • 4 tasks
  • Rust
  • In the all labs plan

The first 2 chapters of Rust are free. This one comes with the all labs plan.

Why you need this

The collection box is no longer one small program. It has the rate charts, the slips, the analyser's parser, the error types, the shift report, and soon the uploads to the plant: by the end of this lab, thousands of lines. Farhan, Lakhan and Neha all change it, and Neha's payout run wants to use the rate charts and the slips without the rest of the box.

Everything so far has lived in a handful of files that main.rs declares with mod and calls with pub functions, two words chapter 4 asked you to take on trust. With only that, every function is either private to its file or callable by anyone, and every field you made pub can be set by anyone to anything: a tank with more milk than it holds, a ledger whose total disagrees with its payments. Callers must know which file each type lives in (crate::slip::Slip), so moving a type breaks them all. And nothing tells you that a loop could be one line, or that a comment no longer matches the code. This chapter is about the shape of a real crate: modules, privacy, paths, and the tools Cargo gives you to keep it tidy.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    rates.rs: a public API and a private helper

    In rates.rs, write pub fn per_litre(kind: Kind, fat: u32, snf: u32) -> u64, what a litre is worth (fat * fat_paise + snf * snf_paise from doodh::rate(kind)), and pub fn amount(kind: Kind, ml: u32, fat: u32, snf: u32) -> u64, what a can earns: 0 when fat is below the chart's min_fat or SNF below its min_snf, else rounded(ml, per_litre(..)). The helper fn rounded(ml: u32, per_litre: u64) -> u64 gives ml * per_litre / 1000 to the nearest paisa (add 500 before dividing). It is only a helper of this module: make it private (the starter has it pub).

    The Check expects per_litre(Kind::Cow, 40, 85) 2980, per_litre(Kind::Buffalo, 64, 91) 4016 and per_litre(Kind::Cow, 29, 86) 2648; amount(Kind::Buffalo, 5250, 64, 91) 21084, amount(Kind::Cow, 4880, 42, 86) 14952, amount(Kind::Cow, 3310, 29, 86) 0 (fat below 30) and amount(Kind::Buffalo, 4000, 70, 84) 0 (SNF below 85). It also compares amount with the paise of every one of the day's 10,164 pourings, and builds a copy of your crate with code outside rates.rs that calls crate::rates::rounded, which must not compile because rounded is private.

  2. Task 2

    lib.rs: Slip, re-exported at the crate's root

    lib.rs is this library's root: its mod lines make each file a module. Add a pub use line that re-exports the slip module's Slip at the crate's root, so code can write crate::Slip (and modules_and_cargo::Slip from another crate). Keep the slip module itself private (mod slip, not pub mod slip), and keep the //! doc comment that starts lib.rs.

    The Check builds a copy of your crate with code that says use crate::Slip and calls Slip::from_collection and line() on the day's second pouring, and reads lib.rs for a pub use line, for no pub mod slip, and for the //! comment at its top.

  3. Task 3

    money.rs: move paise_text into its own module

    paise_text(paise: u64) -> String (21084 is "₹210.84") is defined in report.rs, but slips and reports both use it. Move it, with its doc comment, into money.rs and make it pub(crate) (usable anywhere in this crate, not outside it). Delete it from report.rs, and give report.rs and slip.rs the use lines they now need (both call it). lib.rs already has mod money.

    The Check builds a copy of your crate that calls crate::money::paise_text and expects "₹210.84" for 21084, "₹0.05" for 5 and "₹124158.97" for 12415897. It reads report.rs to make sure it no longer defines paise_text and money.rs for pub(crate) fn paise_text, and expects report::summary(&day, "S002") still to be "S002: 64 pourings, ₹20802.41" and Slip's line() for the day's first pouring to be farmer, ml, "ml" and the paise as rupees, as before.

  4. Task 4 · interview question

    Interview: ledger.rs, the ledger anyone could change

    Ledger in ledger.rs keeps a farmer's ten-day payout, in two fields, paise: u64 and entries: u32, which are pub in the starter. Make both private and write its four pub methods: new() -> Self starts at 0 paise and 0 entries; pay(&mut self, paise: u64) adds the paise and counts one entry; paise(&self) -> u64 and entries(&self) -> u32 return them.

    The Check expects new() to give paise() 0 and entries() 0; after pay(21084) and pay(11650), 32734 and 2; after ten more pay(100), 33734 and 12. It builds two copies of your crate with code outside ledger.rs that sets ledger.paise and reads ledger.entries directly: neither may compile.

    Farhan will ask: why is everything in Rust private unless you write pub, and what did private fields protect here?

What you will learn

  • mod: a module, a named box of code, inline or one file each.
  • Private by default: pub, pub(crate), and why Rust hides everything you do not open.
  • use and paths: crate::, super:: and self::.
  • pub use: re-exporting a name where callers should find it.
  • lib.rs: a library crate's root, built with cargo build and cargo test.
  • Cargo.toml dependencies: adding one of the lab's offline crates.
  • cargo fmt, cargo clippy and doc comments: formatting, lints and cargo doc.

More in Real programs

Build "Modules and Cargo" yourself

DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Rust are free. This one comes with the all labs plan.