cfg
可以通过两种不同的运算符进行配置条件检查
cfg
属性:属性位置的#[cfg(...)]
cfg!
宏:布尔表达式中的cfg!(...)
前者允许条件编译,而后者有条件地评估为 true
或 false
字面量,从而允许在运行时进行检查。两者都使用相同的参数语法。
与 #[cfg]
不同,cfg!
不会删除任何代码,只会评估为 true 或 false。例如,当 cfg!
用于条件时,if/else 表达式中的所有代码块都需要有效,而不管 cfg!
的评估结果是什么。
// This function only gets compiled if the target OS is linux #[cfg(target_os = "linux")] fn are_you_on_linux() { println!("You are running linux!"); } // And this function only gets compiled if the target OS is *not* linux #[cfg(not(target_os = "linux"))] fn are_you_on_linux() { println!("You are *not* running linux!"); } fn main() { are_you_on_linux(); println!("Are you sure?"); if cfg!(target_os = "linux") { println!("Yes. It's definitely linux!"); } else { println!("Yes. It's definitely *not* linux!"); } }