1 个不稳定版本
0.0.1 | 2024年6月20日 |
---|
#16 在 #exclusive
8KB
61 代码行
cfg-feature
一个进程宏,用于确保一次只启用一组特性中的一个。
通常,特性应该是累加的。然而,有时这不可能或不是所希望的。
对于此类情况,如果特性的数量很少,或者不经常改变/发展,一些冗长的 #[cfg]
属性可能足够。
问题
例如,想象一个虚构的crate,它只能与特性 feat1
或 feat2
之一一起构建。
可以创建一个如 build.rs
的构建脚本。
fn main() {
#[cfg(all(feature = "feat1", feature = "feat2"))]
compile_error!("Only one of the features can be enabled at a time");
}
现在想象,我们添加了 feat3
。
我们的 build.rs
更改为
fn main() {
#[cfg(any(
all(feature = "feat1", any(feature = "feat2", feature = "feat3")),
all(feature = "feat2", any(feature = "feat1", feature = "feat3")),
all(feature = "feat3", any(feature = "feat1", feature = "feat2")),
))]
compile_error!("Only one of the features can be enabled at a time");
}
添加第四个 feat4
会变成 12 种组合!
fn main() {
#[cfg(any(
all(feature = "feat1", any(feature = "feat2", feature = "feat3", feature = "feat4")),
all(feature = "feat2", any(feature = "feat1", feature = "feat3", feature = "feat4")),
all(feature = "feat3", any(feature = "feat1", feature = "feat2", feature = "feat4")),
all(feature = "feat4", any(feature = "feat1", feature = "feat2", feature = "feat3")),
))]
compile_error!("Only one of the features can be enabled at a time");
}
这很快就变得难以控制。
解决方案
从两个特性开始,可以使用 cfg-exclusive
进程宏来简化 build.rs
脚本。
cfg_exclusive::cfg_exclusive! {
validate_feats,
["feat1", "feat2"],
"Only one of the features can be enabled at a time"
}
fn main() {
validate_feats();
}
如果特性变为三个
- ["feat1", "feat2"],
+ ["feat1", "feat2", "feat3"],
或者四个
- ["feat1", "feat2", "feat3"],
+ ["feat1", "feat2", "feat3", "feat4"],
许可证
此crate可以按照您选择的许可证之一进行许可
任选其一。
贡献
除非您明确说明,否则您有意提交给工作以供包括在内的任何贡献,根据Apache-2.0许可证定义,应作为上述双许可证提供,不附加任何额外条款或条件。
依赖项
~260–710KB
~17K SLoC