Conditional compilation uses Rust’s cfg attribute to include or exclude an item according to a configuration condition. The condition can describe testing or a target operating system. section 13.1.5
Common uses include:
- Place #[cfg(test)] above test code so it is compiled only while testing. section 13.1.5 section 14.2.3
- Place #[cfg(target_os = "windows")] above code intended only for Windows; equivalent conditions can target Linux or other systems. section 13.1.5
- Combine #[cfg(test)] with a module to keep several tests together while excluding the whole module outside testing. section 14.2.3
A test-only module
A usual pattern places #[cfg(test)] above a tests module, imports surrounding items with use super::*, and keeps #[test] above each test function. The module is omitted when the program is not being tested. section 14.2.3
fn return_two() -> i8 {
2
}
fn return_six() -> i8 {
4 + return_two()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_returns_six() {
assert_eq!(return_six(), 6)
}
#[test]
fn it_returns_two() {
assert_eq!(return_two(), 2);
}
}
Inspect the complete example showing cfg(test), a test module, use super::*, and two test functions. section 14.2.3




