What is the proper way to use the `cfg!` macro to choose between multiple implementations?

自闭症网瘾萝莉.ら 提交于 2020-01-20 09:04:44

问题


I have specified a few features inside Cargo.toml:

[features]
complex = []
simple = []

When I build my project I use cargo build --features="complex" or simple.

In some functions, I want to return a value based on which feature is used:

fn test() -> u32 {
    let x: u32 = 3;
    if cfg!(feature = "complex") {
        let y: u32 = 2;
        x + y
    }
    if cfg!(feature = "simple") {
        let y: u32 = 1;
        x + y
    }
}

But this doesn't work as it tries to evaluate both expressions. What is the proper way to use the cfg! macro in my case?


回答1:


The documentation for cfg! states:

Boolean evaluation of configuration flags.

That means that cfg!(...) is replaced with a Boolean (true / false). Your code would look something like this, after it's expanded:

fn test() -> u32 {
    let x = 3;
    if true {
        let y = 2;
        x + y
    }
    if true {
        let y = 1;
        x + y
    }
}

The easiest solution is to add an else:

fn test() -> u32 {
    let x = 3;
    if cfg!(feature = "complex") {
        let y = 2;
        x + y
    } else {
        let y = 1;
        x + y
    }
}

You can also use the attribute form of cfg. In this case, the attribute can prevent the entire next expression from being compiled:

fn test() -> u32 {
    let x: u32 = 3;

    #[cfg(feature = "complex")]
    {
        let y: u32 = 2;
        x + y
    }

    #[cfg(feature = "simple")]
    {
        let y: u32 = 1;
        x + y
    }
}

as it tries to evaluate both expressions.

No, it doesn't. Evaluation occurs at run-time, and this code cannot even be compiled.

See also:

  • Is it possible to conditionally compile a code block inside a function?
  • Example of how to use Conditional Compilation Macros in Rust
  • How many lines are covered by the Rust conditional compilation attribute?


来源:https://stackoverflow.com/questions/48139243/what-is-the-proper-way-to-use-the-cfg-macro-to-choose-between-multiple-implem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!