默认情况下是否启用可选依赖项?

时间:2020-02-16 21:16:30

标签: rust rust-cargo

如果我定义类似foo = { version = "1.0.0", optional = true }的依赖项, 当我执行“货运”时可以使用吗?我可以检查代码中是否启用了该功能吗?

if cfg!(feature = "foo") {}

似乎无法正常工作,就像该功能一直缺失一样。

1 个答案:

答案 0 :(得分:2)

在此处将答案移至60258216:

可选的依赖项兼具以下功能:https://stackoverflow.com/a/39759592/8182118

尽管您可以使用cargo run --features foo启用该功能,但是默认情况下unless they're listed in the default feature不会启用它们。

为了清楚和向前兼容,您可能想要创建一个实际的功能来启用依赖关系,这样,如果您将来需要“增加”功能并且需要新的可选依赖关系,那么会容易得多。

在代码中,#[cfg]cfg!都应工作,这取决于您是要在编译时还是在运行时进行检查。

测试也不难:

[package]
name = "testx"
version = "0.1.0"
edition = "2018"

[features]
default = ["boolinator"]
magic = ["boolinator"]
empty = []

[dependencies]
boolinator = { version = "*", optional = true }

和main.rs:

fn main() {
    # macro and attributes would work the same here
    if cfg!(feature = "boolinator") {
        println!("Hello, bool!");
    } else {
        println!("Hello, world!");
    }
}

你得到

$ cargo run -q
Hello, bool!
$ cargo run -q --no-default-features
Hello, world!
$ cargo run -q --no-default-features --features boolinator
Hello, bool!
$ cargo run -q --no-default-features --features magic
Hello, bool!
$ cargo run -q --no-default-features --features empty
Hello, world!

另请参阅https://github.com/rust-lang/edition-guide/issues/96

相关问题