Rust 编程: 条件编译-Features
Rust 支持条件编译,可通过两种不同的操作实现:
-
cfg
属性:在属性位置中使用 #[cfg(...)]
-
cfg!
宏:在布尔表达式中使用 cfg!(...)
// 根据操作系统引用不同文件的相同模块
#[cfg_attr(target_os = "linux", path = "linux.rs")]
#[cfg_attr(windows, path = "windows.rs")]
mod os;
// 函数仅当操作系统是 Linux 的时候才会编译
#[cfg(target_os = "linux")]
fn do_on_linux() {
println!("You are running linux!")
}
// 函数仅当操作系统不是 Linux 的时候才会编译
#[cfg(not(target_os = "linux"))]
fn do_on_notlinux() {
println!("You are *not* running linux!")
}
if cfg!(target_os = "windows") {
// windows系统要执行的代码段
} else if cfg!(target_os = "linux") {
// linux系统要执行的代码段
}
// 依赖自设条件是否引用模块 foo
#[cfg(feature = "foo")]
mod foo;
1.