Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the consequences of a feature-gated enum variant?

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?

like image 304
RBF06 Avatar asked Dec 08 '25 06:12

RBF06


1 Answers

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.

like image 163
Cerberus Avatar answered Dec 09 '25 18:12

Cerberus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!