Loading
0xA0Lesson 11 of 17

Modules, Cargo, and testing workflow

Organize code into modules and validate behavior with tests.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Split logic into reusable functions and run basic unit tests.

Modules (mod) organize code and control visibility with pub. Cargo manages builds and tests. Unit tests live in #[cfg(test)] modules and run with cargo test.

main.rs
1fn add(a: i32, b: i32) -> i32 {
2    a + b
3}
4
5#[cfg(test)]
6mod tests {
7    use super::add;
8
9    #[test]
10    fn adds_numbers() {
11        assert_eq!(add(2, 3), 5);
12    }
13}
14
15fn main() {
16    println!("{}", add(4, 1));
17}
Output
5

Testing early is part of Rust fundamentals. Fast cargo test feedback keeps refactors safe as your modules grow.

Try it

Up to 15 XP

Cargo test workflow

Follow the flow from writing a test to seeing a passing/failing result.

Message 1 of 4Predicted 0/0
Developer
cargo test
Compiled test binary

Key takeaways

  • Split logic into reusable functions and run basic unit tests.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Reusable absolute difference

+25 XP

Implement abs_diff(a, b) and print the absolute difference.

  • Positive difference
  • Swapped order
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…