Rust by Example

11.2.1 Custom

Some conditionals like target_os are implicitly provided by rustc, but custom conditionals must be passed to rustc using the --cfg flag.

// custom.rs
#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!")
}

fn main() {
    conditional_function();
}

Without the custom cfg flag:

$ rustc custom.rs && ./custom
custom.rs:7:5: 7:25 error: unresolved name `conditional_function`
custom.rs:7     conditional_function();
                ^~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

With the custom cfg flag:

$ rustc --cfg some_condition custom.rs && ./custom
condition met!