Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ PACKAGES, FILES & TOOLS
BUILD NOTE 30 / 53

Build a navigable codebase.

Organize code and expose only the API callers need.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A crate is a compilation unit. A package may contain a library crate and binary crates. Modules organize names and privacy within a crate; use brings a path into scope but does not download a dependency. Items are private by default, and pub exposes an item according to its containing module visibility. Real packages can place modules in separate files using mod declarations. Keep a small public surface and put implementation details behind functions so internal refactoring does not force every caller to change.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/modules/src/main.rs
mod pricing {
    fn tax(cents: u32) -> u32 {
        cents / 10
    }
    pub fn total(cents: u32) -> u32 {
        cents + tax(cents)
    }
}
use pricing::total;
fn main() {
    println!("{}", total(1000));
}
↳ EXPECTED OUTPUT
1100
  1. 1

    tax remains an implementation detail.

  2. 2

    total is explicitly public.

  3. 3

    use introduces the function name in the caller’s scope.

From the extracted rust-workbench folder
cargo run -p lesson_modules

03 Mind the boundary

04 Your next build

A SMALL MISSION

Create a text module exposing a trim-and-uppercase function.

Reveal one possible solution +
solutions/modules/src/main.rs
mod text {
    pub fn normalize(s: &str) -> String {
        s.trim().to_uppercase()
    }
}
fn main() {
    assert_eq!(text::normalize(" rust "), "RUST");
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does use add a crate dependency to Cargo.toml?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.