Conditional compilation uses Rust’s cfg attribute macro to compile or skip an item under a particular configuration. It can select OS-specific functions, include optional crate features, or keep test code out of production builds. section 7.1 section 6.3
Attach cfg to different kinds of Rust items:
- Use #[cfg(test)] on a module so its contents compile only during test builds. section 7.1
- Apply cfg to functions, structs, traits, blocks, or modules. section 7.1
- Use Cargo features to enable alternate code paths, additional dependencies, or dependency features. section 6.3
- Create custom conditional compilation flags when users need to include or exclude whole features. section 7.1
Keeping tests out of production builds
Place unit tests in a nearby module marked #[cfg(test)]: #[cfg(test)] mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } } Cargo compiles, discovers, and runs this module with cargo test. Ordinary library or executable builds omit the module, reducing production code and avoiding accidental use of test-only values or functions. section 7.1 section 7.3
Listing 7.1 Contents of a newly initialized Rust library
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}
Inspect the complete initialized Rust test module, including cfg(test), #[test], and an assertion. section 7.1




