module-concept

Rust Conditional module compilation

Select source items at compile time. Unlike an ordinary if expression, a false cfg removes the annotated item from compilation. A custom flag can be passed by the compiler or controlled through Cargo features. Expected result (not executed): base Why: The empty any predicate is false; only the fallback module is compiled. Common mistake: Calling a disabled item without guarding the call as well.

Formal Syntax & Structure

rust syntaxrust
#[cfg(predicate)] mod name {}

Working Example

Example Snippetrust
#[cfg(any())]mod optional { pub fn mode() -> &'static str { "extra" } }#[cfg(not(any()))]mod optional { pub fn mode() -> &'static str { "base" } }fn main() { println!("{}", optional::mode()); }
Rust Reference