Rust Tutorial · Projects and Testing · Lesson 27 of 29
Rust Modules, Crates and Cargo
Organise code into modules, control visibility with pub, and use external crates from crates.io.
Modules
mod groups code; items are private by default and pub makes them visible. In a project, mod billing;
loads src/billing.rs. use brings names into scope.
mod billing {
pub struct Invoice { pub number: u32, total_cents: u64 }
impl Invoice {
pub fn new(number: u32, items: &[u64]) -> Self {
Invoice { number, total_cents: items.iter().sum() }
}
pub fn total(&self) -> String { format!("{}.{:02}", self.total_cents / 100, self.total_cents % 100) }
}
pub mod tax {
pub fn vat(cents: u64) -> u64 { cents * 20 / 100 }
}
}
use billing::{tax, Invoice};
fn main() {
let invoice = Invoice::new(1001, &[1_250, 899]);
println!("invoice {} total {}", invoice.number, invoice.total());
println!("vat on 10.00: {}", tax::vat(1_000));
// println!("{}", invoice.total_cents); // error: field is private
}
Output
invoice 1001 total 21.49 vat on 10.00: 200
Run this on your computer — see “Get Started” for setup.
Crates and dependencies
A crate is a compilation unit: a binary (src/main.rs) or a library (src/lib.rs). Add dependencies with
cargo add, which edits Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Popular crates: serde (serialization), tokio (async runtime), axum (web), reqwest (HTTP client),
sqlx (databases), clap (CLI arguments), anyhow/thiserror (errors), tracing (logging).
Test yourself
What is the default visibility of items inside a Rust module?
PublicPrivate to the moduleVisible to the crateVisible to tests only
Show answer
Answer: Private to the module