Build a navigable codebase.
Organize code and expose only the API callers need.
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.
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));
}1100
- 1
tax remains an implementation detail.
- 2
total is explicitly public.
- 3
use introduces the function name in the caller’s scope.
cargo run -p lesson_modules03 Mind the boundary
04 Your next build
Create a text module exposing a trim-and-uppercase function.
Reveal one possible solution +
mod text {
pub fn normalize(s: &str) -> String {
s.trim().to_uppercase()
}
}
fn main() {
assert_eq!(text::normalize(" rust "), "RUST");
}05 Check your reasoning
Does use add a crate dependency to Cargo.toml?
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.