代码点读机 / Rust / cfg!

cfg! Rust · 宏

在编译期检查当前构建配置条件,返回 bool,用于写跨平台或条件分支代码。

怎么用

cfg!(条件);,用于编译期条件判断

小例子

let b = cfg!(target_os = "windows")
    || cfg!(target_os = "linux")
    || cfg!(target_os = "macos");
println!("{}", b);

运行结果

true

提醒:条件与 #[cfg(...)] 属性使用的相同;常用 target_os、target_arch 等

官方文档:https://doc.rust-lang.org/std/macro.cfg.html

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Rust全部词条