Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...