Modules, Cargo, and testing workflow
Organize code into modules and validate behavior with tests.
- 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.
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}5
Testing early is part of Rust fundamentals. Fast cargo test feedback keeps refactors safe as your modules grow.
Try it
Up to 15 XPCargo test workflow
Follow the flow from writing a test to seeing a passing/failing result.
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.
Reusable absolute difference
Implement abs_diff(a, b) and print the absolute difference.
- Positive difference
- Swapped order
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…