英文:
What are the consequences of a feature-gated enum variant?
问题
如果一个库 crate 定义了一个具有 feature 门控的变体的枚举 enum 会怎样?
#[non_exhaustive]
enum Foo {
A,
B,
#[cfg(feature = "some-feature")]
Gated,
}
这是一个试图允许 enum Foo 支持可选 feature,具有 Gated 变体的朴素尝试,同时也允许不需要该 feature 的客户端通过禁用 crate feature some-feature 来排除与之相关的成本。
这样做可能涉及到哪些潜在危险和/或成本?是否有令人信服的理由避免这种模式?
英文:
What if a library crate defines an enum that has a variant that is feature-gated?
#[non_exhaustive]
enum Foo {
A,
B,
#[cfg(feature = "some-feature")]
Gated,
}
This is a naïve attempt to allow the enum Foo to support the optional feature with the Gated variant, while also allowing clients who do not need the feature to opt out of the costs associated with it (by disabling the crate feature some-feature).
What are the potential dangers and/or costs associated with doing this? Are there any compelling reasons for avoiding this pattern?
答案1
得分: 3
如果枚举没有标记为#[non_exhaustive],这可能会导致二进制 crate 端出现意外且无法解决的问题。
想象以下情况:
- 您的库
foo导出此枚举:
pub enum Foo {
A,
B,
#[cfg(feature = "some-feature")]
Gated,
}
- 库
bar依赖于foo,但没有使用特性,并在foo::Foo上进行匹配,处理Foo::A和Foo::B,而忽略Foo::Gated,因为在此配置中它不存在。 - 二进制 crate
baz既依赖于bar又依赖于foo,并且启用了特性。
然后,bar 本身可以正常工作,但尝试构建 baz 将会失败,因为特性会在依赖树上统一,当启用 some-feature 时,bar 会出现问题。
英文:
If the enum is not marked with #[non_exhaustive], this may lead to an unexpected and effectively unsolvable breakage on the binary crate's side.
Imagine the following case:
- Your library
fooexports this enum:
pub enum Foo {
A,
B,
#[cfg(feature = "some-feature")]
Gated,
}
- Library
bardepends onfoowithout feature and matches onfoo::Foo, handlingFoo::AandFoo::Band ignoringFoo::Gated, since it doesn't exist in this confiuguration. - Binary
bazdepends both onbarand onfoo, with feature.
Then, bar by itself works fine, but attempt to build baz will fail, since features will be unified across dependency tree, and when some-feature is active, bar breaks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论