如果我定义一个像 的依赖项foo = { version = "1.0.0", optional = true }
,当我执行“cargo run”时它会可用吗?我可以检查它是否在代码中启用吗?
if cfg!(feature = "foo") {}
Run Code Online (Sandbox Code Playgroud)
似乎不起作用,就像该功能一直缺失一样。
将答案移至 60258216 此处:
可选依赖项兼作功能:/sf/answers/2783171471/
默认情况下不会启用它们,除非它们在default
功能中列出,但您可以使用 来启用该功能cargo run --features foo
。
为了清楚起见和向前兼容性,您可能希望创建一个启用依赖项的实际功能,这样,如果您将来需要“弄乱”该功能并且需要新的可选依赖项,那就容易多了。
在代码中, 和#[cfg]
都cfg!
应该起作用,具体取决于您是要在编译时还是运行时检查它。
测试也不难:
[package]
name = "testx"
version = "0.1.0"
edition = "2018"
[features]
default = ["boolinator"]
magic = ["boolinator"]
empty = []
[dependencies]
boolinator = { version = "*", optional = true }
Run Code Online (Sandbox Code Playgroud)
和一个 main.rs :
[package]
name = "testx"
version = "0.1.0"
edition = "2018"
[features]
default = ["boolinator"]
magic = ["boolinator"]
empty = []
[dependencies]
boolinator = { version = "*", optional = true }
Run Code Online (Sandbox Code Playgroud)
你得到
fn main() {
# macro and attributes would work the same here
if cfg!(feature = "boolinator") {
println!("Hello, bool!");
} else {
println!("Hello, world!");
}
}
Run Code Online (Sandbox Code Playgroud)
另请参阅https://github.com/rust-lang/edition-guide/issues/96
归档时间: |
|
查看次数: |
2079 次 |
最近记录: |