我正在尝试测试是否已使用宏设置了我的依赖项之一的功能cfg!。
下面是一个例子:
my-lib/Cargo.toml
[package]
name = "my-lib"
version = "0.1.0"
edition = "2018"
[features]
some-feature = []
Run Code Online (Sandbox Code Playgroud)
my-lib/lib.rs
[package]
name = "my-lib"
version = "0.1.0"
edition = "2018"
[features]
some-feature = []
Run Code Online (Sandbox Code Playgroud)
my-bin/Cargo.toml
[package]
name = "my-bin"
version = "0.1.0"
edition = "2018"
[dependencies]
my-lib = { path = "../my-lib" }
Run Code Online (Sandbox Code Playgroud)
my-bin/main.rs
pub fn some_function() {
if cfg!(feature = "some-feature") {
println!("SET");
} else {
println!("NOT SET");
}
}
Run Code Online (Sandbox Code Playgroud)
下面显示了不同运行条件下的输出。我预计会出现第二种情况is SET in bin。
> cargo run --features ""
NOT SET
is NOT SET in bin
Run Code Online (Sandbox Code Playgroud)
> cargo run --features "my-lib/some-feature"
SET
is NOT SET in bin
Run Code Online (Sandbox Code Playgroud)
解决方法是添加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
Run Code Online (Sandbox Code Playgroud)