特性门控的枚举变体有哪些后果?

huangapple go评论47阅读模式
英文:

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::AFoo::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 foo exports this enum:
pub enum Foo {
    A,
    B,
    #[cfg(feature = "some-feature")]
    Gated,
}
  • Library bar depends on foo without feature and matches on foo::Foo, handling Foo::A and Foo::B and ignoring Foo::Gated, since it doesn't exist in this confiuguration.
  • Binary baz depends both on bar and on foo, 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.

huangapple
  • 本文由 发表于 2023年3月1日 11:33:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定