Cargo 自行激活功能

Cargo activates features by itself

我有一个依赖库的二进制文件。在库中,我指定了这些功能:

[features]
default = []
fet = []

我希望功能 fet 只有在使用功能标志编译时才会被激活。在我的二进制文件中,Cargo.toml 看起来像这样:

[dependencies]
a = { path = "./a" }

[features]
default = []

我没有在 Cargo.toml 中指定 fet 功能,但是这给我的二进制文件带来了编译错误:

fn main() {
    if cfg!(feature = "fet") {
        compile_error!("not expected");
    }
}

为什么功能 fet 在我的二进制文件中仍然处于激活状态?我执行了这些命令并得到了同样的错误:

cargo run
cargo run --features=default

理想情况下,如果 cargo run 命令(在 --features 标志中)明确提及,我希望我的二进制文件从依赖项中激活某些功能。这可能吗?我希望这能在我的二进制 Cargo.toml:

中工作
[features]
default = []
fet = ["a/fet"]

如果我 运行 这个命令,功能 fet 将被激活:

cargo run --features=fet

cfg! 宏将根据条件为真或假扩展为 truefalse,因此如果未设置功能标志,它仍会扩展对此:

fn main() {
    if false {
        compile_error!("not expected");
    }
}

compile_error! 宏仍会被调用,因此无论哪种方式都会出现编译器错误。

当您可以依靠编译器优化永远不会被采用的分支(例如 if false 分支)时,cfg! 宏最有用。不过,代码在优化之前仍需要编译,因此当代码仅在条件为真或假时编译时,它的用处不大。

您想要使用的是 #[cfg] attribute or the cfg_if::cfg_if! 宏:

// with #[cfg] attribute

fn main() {
    #[cfg(feature = "fet")]
    compile_error!("not expected");
}

// with cfg_if!
use cfg_if::cfg_if;

fn main() {
    cfg_if!{
        if #[cfg(feature = "fet")] {
            compile_error!("not expected");
        }
    }
}