您可以测试是否使用`cfg!`宏设置了依赖项的功能吗?

时间:2019-09-04 17:03:47

标签: rust rust-cargo

我正在尝试测试是否已使用cfg!宏设置了我的一个依赖项的功能。

下面是一个示例:

my-lib / Cargo.toml

[package]
name = "my-lib"
version = "0.1.0"
edition = "2018"

[features]
some-feature = []

my-lib / lib.rs

pub fn some_function() {
    if cfg!(feature = "some-feature") {
        println!("SET");
    } else {
        println!("NOT SET");
    }
}

my-bin / Cargo.toml

[package]
name = "my-bin"
version = "0.1.0"
edition = "2018"

[dependencies]
my-lib = { path = "../my-lib" }

my-bin / main.rs

use my_lib;

fn main() {
    my_lib::some_function();

    if cfg!(feature = "my-lib/some-feature") {
        println!("is SET in bin");
    } else {
        println!("is NOT SET in bin");
    }
}

下面显示了在不同运行条件下的输出。我希望第二种情况显示is SET in bin

> cargo run --features ""
NOT SET
is NOT SET in bin
> cargo run --features "my-lib/some-feature"
SET
is NOT SET in bin

一种解决方法是将bin-some-feature = ["my-lib/some-feature"]添加到“ my-bin / Cargo.toml”,并将“ my-bin / main.rs”中的支票更改为cfg!(feature = "bin-some-feature")。这样会产生所需的输出。

> cargo run --features "bin-some-feature"
SET
is SET in bin

0 个答案:

没有答案