• rust 条件编译


    条件编译可以通过两种不同的操作符实现,如下:
    
    -   cfg属性:在属性位置中使用#[cfg(...)]
    
    -   cfg!宏:在布尔表达式中使用cfg!(...)
     

    Configuration conditional checks are possible through two different operators:

    • the cfg attribute: #[cfg(...)] in attribute position
    • the cfg! macro: cfg!(...) in boolean expressions

    While the former enables conditional compilation, the latter conditionally evaluates to true or false literals allowing for checks at run-time. Both utilize identical argument syntax.

    // This function only gets compiled if the target OS is linux
    #[cfg(target_os = "linux")]
    fn are_you_on_linux() {
        println!("You are running linux!");
    }
    
    // And this function only gets compiled if the target OS is *not* linux
    #[cfg(not(target_os = "linux"))]
    fn are_you_on_linux() {
        println!("You are *not* running linux!");
    }
    
    fn main() {
        are_you_on_linux();
    
        println!("Are you sure?");
        if cfg!(target_os = "linux") {
            println!("Yes. It's definitely linux!");
        } else {
            println!("Yes. It's definitely *not* linux!");
        }
    }
    [root@bogon cfg]# ls
    Cargo.lock  Cargo.toml  README.md  src
    [root@bogon cfg]# cargo build
       Compiling hello_world v0.1.0 (/data2/rust/cfg)
        Finished dev [unoptimized + debuginfo] target(s) in 0.39s
    [root@bogon cfg]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    You are running linux!
    Are you sure?
    Yes. It's definitely linux!
    [root@bogon cfg]# 
    //main.rs
    #[cfg(some_condition)]
    fn conditional_function() {
        println!("condition met!");
    }
    
    fn main() {
        conditional_function();
        println!("Hello, world!");
    }
    
     
    [root@bogon src]# rustc --cfg some_condition main.rs
    [root@bogon src]# ./main
    condition met!
    Hello, world!
    [root@bogon src]# rustc  main.rs
    error[E0425]: cannot find function `conditional_function` in this scope
     --> main.rs:8:5
      |
    8 |     conditional_function();
      |     ^^^^^^^^^^^^^^^^^^^^ not found in this scope
    
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E0425`.
    [root@bogon src]#
  • 相关阅读:
    caption标签,为表格添加标题和摘要
    用css样式,为表格加入边框
    table标签,认识网页上的表格
    给div命名,使逻辑更加清晰
    认识div在排版中的作用
    使用ol,添加图书销售排行榜
    使用ul,添加新闻信息列表
    关于tableView在滚动时存在的偏移量问题
    跳转到微信扫一扫
    文件下载的缓存策略
  • 原文地址:https://www.cnblogs.com/dream397/p/14229765.html
Copyright © 2020-2023  润新知