Modules & Testing
Organizing code with modules and pub, and writing unit tests that live next to the code.
Rust has testing built in: functions marked #[test] are compiled into a test runner with cargo test (or rustc --test). Unit tests usually live in a tests module inside the same file, so they can test private functions too.
A CRC module with tests
pub mod crc groups the CRC code; pub fn makes crc8 visible outside the module.
assert_eq! compares and prints both values on failure.
The check value 0xF4 for '123456789' is the published reference result for CRC-8/SMBUS — a classic way to test a CRC.
Project layout
Testing only with println! in main Write #[test] functions with assert! / assert_eq!
Tests in the test runner are repeatable, run in CI, and fail loudly instead of needing someone to read output.
What does #[cfg(test)] do?
It compiles the annotated item (usually the tests module) only when building tests, so test code and test-only dependencies do not end up in the release binary.