Lesson 10
Modules, Crates and Tests
Every program in this course so far has lived in one file. A real program grows past the point where that is comfortable to read, and it is often built from several packages instead of one. This lesson covers how to split a program into named parts, how to say which of those parts other code is allowed to use, and how to write tests that check your code keeps working as you change it.
Modules in a Program
A module is a named group of items inside a program: functions, structs, enums, or other modules. mod starts one.
mod kitchen {
pub fn bake_bread() {
println!("bread is baking");
}
fn preheat_oven() {
println!("oven is warming");
}
pub fn bake_cake() {
preheat_oven();
println!("cake is baking");
}
}
fn main() {
kitchen::bake_bread();
kitchen::bake_cake();
}
bread is baking
oven is warming
cake is baking
-
mod kitchen { ... }defines a module namedkitchen. The three functions inside it belong to that module. -
Two colons write a path:
kitchen::bake_breadmeans “thebake_breadfunction insidekitchen”. You use a path the same way you use a name, everywhere a name is expected. -
Code inside a module can call other items in the same module directly.
bake_cakecallspreheat_ovenwithout a path, because both are insidekitchen.
Items Are Private by Default
Every item in Rust, a function, a struct, an enum, is private unless you say otherwise. A private item can be used inside the module it is defined in, and inside any module nested in it, but nowhere else. Write pub before an item to make it public: usable from outside the module too.
In the program above, preheat_oven has no pub. It works when bake_cake calls it, because that call is inside kitchen itself. Calling it from main does not compile.
mod kitchen {
fn preheat_oven() {
println!("oven is warming");
}
}
fn main() {
kitchen::preheat_oven();
}
error[E0603]: function `preheat_oven` is private
--> src/main.rs:8:14
|
8 | kitchen::preheat_oven();
| ^^^^^^^^^^^^ private function
|
note: the function `preheat_oven` is defined here
--> src/main.rs:2:5
|
2 | fn preheat_oven() {
| ^^^^^^^^^^^^^^^^^
Key idea
Private by default means a module can change its own inside details, such as
preheat_ovenhere, without breaking any code outside the module. Only what is markedpubis a promise to the rest of the program.
Public Fields on a Struct
pub on a struct makes the struct itself usable from outside the module, but it says nothing about the fields inside. Each field needs its own pub to be readable or writable from outside.
mod menu {
pub struct Order {
pub dish: String,
price_cents: u32,
}
impl Order {
pub fn new(dish: &str, price_cents: u32) -> Order {
Order { dish: String::from(dish), price_cents }
}
pub fn price_cents(&self) -> u32 {
self.price_cents
}
}
}
use menu::Order;
fn main() {
let order = Order::new("soup", 450);
println!("{} costs {} cents", order.dish, order.price_cents());
}
soup costs 450 cents
dish is pub, so order.dish works from main. price_cents is not, so main cannot read it directly.
error[E0616]: field `price_cents` of struct `Order` is private
--> src/main.rs:18:26
|
18 | println!("{}", order.price_cents);
| ^^^^^^^^^^^ private field
This is why Order has a price_cents method: it is the door the module chose to open onto a field it otherwise keeps to itself. The module can later change how the price is stored without breaking any code that only ever called price_cents().
Bringing a Path into Scope with use
Writing menu::Order every time gets long in a bigger program. use brings a path into scope, so you can write the last name on its own after that.
use menu::Order;
fn main() {
let order = Order::new("soup", 450);
// same as menu::Order::new("soup", 450)
}
use can also give an item a different name with as. This matters when two modules have items with the same name and you need both in one file.
mod menu {
pub struct Order {
pub dish: String,
}
}
use menu::Order as MenuItem;
fn main() {
let order = MenuItem { dish: String::from("soup") };
println!("{}", order.dish);
}
soup
MenuItem is now the name main uses for menu::Order. The struct’s own name has not changed, only the name this one file calls it by.
Modules Inside Modules
A module can hold other modules, forming a tree. A path can have more than two parts, one for each level.
mod restaurant {
pub mod kitchen {
pub fn bake_bread() {
println!("bread is baking");
}
}
pub mod front_desk {
use crate::restaurant::kitchen;
pub fn serve_bread() {
kitchen::bake_bread();
println!("bread is served");
}
}
}
fn main() {
restaurant::front_desk::serve_bread();
}
bread is baking
bread is served
restaurant holds two modules, kitchen and front_desk, and both are marked pub so code outside restaurant can reach into them. crate at the front of a path means “start from the top of this program”. crate::restaurant::kitchen is an absolute path: it names the same module no matter which file it is written in. The call inside main, restaurant::front_desk::serve_bread(), is a relative path: it starts from wherever the code already is, which here is the top of the program too.
Splitting a Module into Its Own File
Writing mod kitchen { ... } keeps the module in the same file. Write mod kitchen; instead, with a semicolon and no braces, and Rust looks for the module’s contents in a file of that name.
src
main.rs
kitchen.rs
// src/main.rs
mod kitchen;
fn main() {
kitchen::bake_bread();
}
// src/kitchen.rs
pub fn bake_bread() {
println!("bread is baking");
}
bread is baking
src/kitchen.rs holds exactly what would otherwise sit between the braces of mod kitchen { ... }. Nothing inside it repeats the name kitchen. The file name is what ties it to the mod kitchen; line in main.rs. This is how a program grows past one file without changing how any path is written.
A Module Split Across Several Files
kitchen may itself hold modules of its own, each big enough to deserve its own file. Rust looks for those files in a folder named after the parent module.
src
main.rs
kitchen
mod.rs
bread.rs
// src/main.rs
mod kitchen;
fn main() {
kitchen::bread::bake();
}
// src/kitchen/mod.rs
pub mod bread;
// src/kitchen/bread.rs
pub fn bake() {
println!("bread is baking");
}
bread is baking
mod kitchen; in main.rs still points Rust at a single file, but now that file is kitchen/mod.rs instead of kitchen.rs. Rust looks in the kitchen folder because a file of that exact name, kitchen.rs, does not exist next to it. Inside mod.rs, pub mod bread; works the same way mod kitchen; did in main.rs: it loads kitchen/bread.rs as the contents of a module named bread, nested inside kitchen.
You will often see the same layout written without a mod.rs file at all: a file named kitchen.rs sitting next to a folder named kitchen, holding bread.rs.
src
main.rs
kitchen.rs
kitchen
bread.rs
kitchen.rs here holds exactly what kitchen/mod.rs held above, pub mod bread;, and nothing else changes. Both layouts mean the same thing to the compiler. The second one is more common in new code, because having many files all named mod.rs open at once makes them hard to tell apart in an editor.
Crates and Packages
Two words describe how a Rust program is put together, and beginners often mix them up because English uses them loosely for the same idea.
A crate is what the compiler builds in one pass: either a binary crate, a program with a main function that produces a runnable file, or a library crate, a set of items meant to be used from other crates, with no main.
A package is what Cargo.toml describes: one name, one version, and the crate or crates built from it. cargo new makes a package with exactly one crate. A package may hold both kinds at once: one library crate at src/lib.rs, and one or more binary crates, one at src/main.rs and any others under src/bin/.
greeter
Cargo.toml
src
lib.rs
main.rs
-
src/lib.rsis the root of the library crate. Its public items are what other code, includingmain.rsin the same package, can use. -
src/main.rsis the root of a binary crate. It can bring in the library crate by its package name, the same way any other package would. -
One package, two crates.
cargo buildbuilds both.
A library crate is useful on its own even without a matching binary: it is the shape a package takes when it exists to be used by other packages, rather than run directly.
Workspaces
A workspace is a group of packages that share one build. They are built with one cargo build, share one Cargo.lock file that pins the exact version of every dependency, and put their compiled files in one shared target folder instead of one each.
A workspace starts with a Cargo.toml that has no [package] section of its own, only a [workspace] section naming its members.
diner
Cargo.toml
kitchen
Cargo.toml
src
lib.rs
server
Cargo.toml
src
main.rs
[workspace]
resolver = "3"
members = ["kitchen", "server"]
kitchen and server are ordinary packages, each with its own Cargo.toml. resolver = "3" picks the current rule Cargo uses to work out which versions of shared dependencies to build. server can depend on kitchen by giving its folder as a path.
[dependencies]
kitchen = { path = "../kitchen" }
// server/src/main.rs
fn main() {
println!("serving {}", kitchen::bake_bread());
}
serving bread
Key idea
Use a workspace when one project is naturally several packages that belong together: a library and the program that uses it, or several small tools that share code. Everything in it builds against the same dependency versions, so they cannot quietly drift apart.
Writing Tests
A test is a function that checks a small piece of your code still behaves the way you expect. #[test] marks a function as one. assert_eq! fails the test if its two arguments are not equal.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 2));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 2), 4);
}
#[test]
fn adds_negative_numbers() {
assert_eq!(add(-3, -4), -7);
}
}
Run the tests with cargo test instead of cargo run.
cargo test
running 2 tests
test tests::adds_negative_numbers ... ok
test tests::adds_two_numbers ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
-
#[test]goes directly above a function with no parameters and no return value.cargo testfinds every function marked this way and runs each one. -
assert_eq!(add(2, 2), 4)runsadd(2, 2)and checks the result equals4. If it does not, the test fails and the function stops there, the same waypanic!stops a program. -
assert_ne!is the opposite: it fails if the two arguments are equal.assert!takes one condition and fails when it isfalse.
A Failing Test
When assert_eq! fails, cargo test shows both values so you can see exactly what went wrong.
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 2), 5);
}
running 1 test
test tests::adds_two_numbers ... FAILED
failures:
---- tests::adds_two_numbers stdout ----
thread 'tests::adds_two_numbers' panicked at src/main.rs:15:9:
assertion `left == right` failed
left: 4
right: 5
failures:
tests::adds_two_numbers
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
left is what your code actually produced. right is what you told assert_eq! to expect. A failing test is not a crash in your program, it is the test doing its job: telling you the code and the expectation disagree.
A Test That Should Panic
Some functions are meant to panic on bad input. #[should_panic] marks a test that passes only if the function inside it panics.
pub fn greet(name: &str) -> String {
if name.is_empty() {
panic!("name must not be empty");
}
format!("hello, {name}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greets_by_name() {
assert_eq!(greet("Asha"), "hello, Asha");
}
#[test]
#[should_panic]
fn empty_name_panics() {
greet("");
}
}
running 2 tests
test tests::empty_name_panics - should panic ... ok
test tests::greets_by_name ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
If greet("") had not panicked, this test would fail, because #[should_panic] expects a panic and did not get one.
Organizing Tests Inside a File
#[cfg(test)] tells Rust to build a module only when running tests, so none of the code inside it is included in the program you ship. Tests written this way sit next to the code they test, in the same file, in a module usually named tests.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 2), 4);
}
}
use super::*; brings every public and private item from the module above, here the whole file, into the tests module. A test can use private functions this way, because a nested module can always see into the module holding it. This is how a test can check a private helper function directly, not only the public functions built on top of it.
Integration Tests in Their Own Folder
A test inside #[cfg(test)] mod tests is a unit test: it tests one function or one module from the inside, and it can see private items. An integration test tests a library crate the way another package would use it, through its public items only. It goes in a tests folder next to src, one file per group of tests.
greeter
Cargo.toml
src
lib.rs
tests
greet_tests.rs
// tests/greet_tests.rs
use greeter::greet;
#[test]
fn greets_asha() {
assert_eq!(greet("Asha"), "hello, Asha");
}
Running tests/greet_tests.rs
running 1 test
test greets_asha ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
use greeter::greet; reaches into the library crate by its package name, greeter, exactly as an outside package depending on it would. Only pub items are visible here. cargo test runs the unit tests inside src and every file in tests in the same pass.
Key idea
A unit test checks one piece from the inside and may use private items. An integration test checks the finished library from the outside, through the same public items its users would call.
Everything Together
This program uses the whole lesson in one file: a private module with a public struct, a private field reached through a method, and both a unit test and a check that the price includes tax.
mod till {
pub struct Sale {
pub item: String,
price_cents: u32,
}
impl Sale {
pub fn new(item: &str, price_cents: u32) -> Sale {
Sale { item: String::from(item), price_cents }
}
pub fn total_with_tax(&self) -> u32 {
add_tax(self.price_cents)
}
}
fn add_tax(price_cents: u32) -> u32 {
price_cents + price_cents / 10
}
}
use till::Sale;
fn main() {
let sale = Sale::new("tea", 200);
println!("{} costs {} cents with tax", sale.item, sale.total_with_tax());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_ten_percent_tax() {
let sale = Sale::new("tea", 200);
assert_eq!(sale.total_with_tax(), 220);
}
}
tea costs 220 cents with tax
add_tax is private to till and never marked pub. Nothing outside the module can call it directly, and nothing needs to: it is reached only through total_with_tax, the door the module chose to open. The test in mod tests checks the public behaviour, that a 200 cent sale totals 220 with tax, without knowing or caring that a helper function did the arithmetic.
Reference
| Written as | What it does |
|---|---|
| mod kitchen { … } | Define a module in the same file. |
| mod kitchen; | Load a module’s contents from kitchen.rs. |
| pub fn f() { … } | Make an item usable outside its module. |
| kitchen::bake_bread() | A path: reach an item through its module. |
| crate::path | An absolute path, starting from the top. |
| use menu::Order; | Bring a path into scope under its last name. |
| use menu::Order as X; | Bring a path into scope under a chosen name. |
| [dependencies] | In Cargo.toml, packages this one depends on. |
| [workspace] | In Cargo.toml, lists the member packages. |
| #[test] | Marks a function as a test, run by cargo test. |
| assert_eq!(a, b) | Fail the test if a and b are not equal. |
| assert!(cond) | Fail the test if cond is false. |
| #[should_panic] | The test passes only if the function panics. |
| #[cfg(test)] mod tests | A module built only when running tests. |
| cargo test | Build and run every test in the package. |
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →