无需在Crate A声明特性,能否直接使用Crate B的b_feature?
问题解答
可行,Rust 支持直接在当前 crate 中引用依赖 crate 的特性做条件编译,无需在当前 crate 的 Cargo.toml 里重新声明对应特性。
具体写法:
- Rust 1.60 及以上版本支持简洁语法:
#[cfg(feature = "B/b_feature")] - 旧版本可以用更明确的写法:
#[cfg(feature = "b_feature", package = "B")]
启用依赖特性的方式:
虽然不用在 Crate A 的 Cargo.toml 里新增特性,但要让 A 编译时触发 B 的 b_feature,需要通过以下方式之一:
- 构建时通过命令行传递特性:
cargo build --features B/b_feature - 若在工作空间中,也可以在根 Cargo.toml 里统一配置,但这不属于在 A 中新增特性的范畴。
代码示例:
在 Crate A 的代码里直接使用条件编译:
#[cfg(feature = "B/b_feature")] fn use_b_special_func() { // 调用 Crate B 中仅在 b_feature 启用时暴露的功能 B::special_function(); }
内容的提问来源于stack exchange,提问作者tkachuko
相关产品推荐
相关产品推荐

