【Rust】屬性-cfg


環境

  • 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 中怎么使用屬性來進行條件編譯。

附錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM