feature就相当于项目的不同版本形态,比如一个项目,有两个版本:
- feature1,默认版,提供默认功能
- feature2,豪华版,提供更多高级功能
那么在代码中,就可以针对不同的版本写不同的代码,这样:
#[cfg(feature = "feature1")] fn some_function() { // 在 feature1 启用时执行的代码 } #[cfg(feature = "feature2")] fn another_function() { // 在 feature2 启用时执行的代码 }
然后在Cargo.toml中,配置对应feature需要的依赖,没错,不同的feature依赖可能不同。
其中default对应默认的feature,即在编译时如果不指定–feature,则会选用default。
[features] default = ["default dependency"] feature1 = ["dependency1 for feature1"] feature2 = ["dependency2 for feature1"]
然后编译时,可以指定编译成什么版本:
cargo build --features "feature1"
还可以编译同时包含多种feature的产品,比如:
cargo build --features "feature1,feature2"
这将启用 feature1 和 feature2 特性,并构建相应的代码。
此外,还可以在dependencies中指定feature。比如一个依赖项,有多个feature,可以选择依赖于指定的feature:
[dependencies] crate-name = { version = "1.0", features = ["feature1", "feature2"] }
发表回复