cfg

条件编译可能通过两种不同的操作符实现:

  • cfg 属性:在属性位置中使用 #[cfg(...)]
  • cfg! 宏:在布尔表达式中使用 cfg!(...)

两种形式使用的参数语法都相同。

  1. // 这个函数仅当目标系统是 Linux 的时候才会编译
  2. #[cfg(target_os = "linux")]
  3. fn are_you_on_linux() {
  4. println!("You are running linux!")
  5. }
  6. // 而这个函数仅当目标系统 **不是** Linux 时才会编译
  7. #[cfg(not(target_os = "linux"))]
  8. fn are_you_on_linux() {
  9. println!("You are *not* running linux!")
  10. }
  11. fn main() {
  12. are_you_on_linux();
  13. println!("Are you sure?");
  14. if cfg!(target_os = "linux") {
  15. println!("Yes. It's definitely linux!");
  16. } else {
  17. println!("Yes. It's definitely *not* linux!");
  18. }
  19. }

参见:

引用, cfg!, 和 .