環境
- Rust 1.56.1
- VSCode 1.61.2
概念
參考:https://doc.rust-lang.org/stable/rust-by-example/attribute/cfg.html
示例
屬性配置
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!");
}
// target_os 是 rust 自動傳遞的
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
println!("You are *not* running linux!");
}
fn main() {
are_you_on_linux();
}
宏配置
target_os 由 rust 自動傳入。
fn main() {
println!("Are you sure?");
if cfg!(target_os = "linux") {
println!("Yes. It's definitely linux!");
} else {
println!("Yes. It's definitely *not* linux!");
}
}
總結
了解了 Rust 中怎么使用屬性來進行條件編譯。
