Is it possible to conditionally compile a code block inside a function?

前端 未结 2 1899
日久生厌
日久生厌 2021-01-21 01:36

I\'m wondering if something like this is possible

fn main() {
    #[cfg(foo)] {
        println!(\"using foo config\");
    }

}

The context is

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 01:44

    As of at least Rust 1.21.1, it's possible to do this as exactly as you said:

    fn main() {
        #[cfg(foo)]
        {
            println!("using foo config");
        }
    }
    

    Before this, it isn't possible to do this completely conditionally (i.e. avoiding the block being type checked entirely), doing that is covered by RFC #16. However, you can use the cfg macro which evaluates to either true or false based on the --cfg flags:

    fn main() {
        if cfg!(foo) { // either `if true { ... }` or `if false { ... }`
            println!("using foo config");
        }
    }
    

    The body of the if always has name-resolution and type checking run, so may not always work.

提交回复
热议问题