[][src]Crate enhanced_enum

Enhanced Fieldless Enumerations and Associated Array Types

In Rust, enumerations can contain data fields which is a powerful language feature. However not all enums have data fields. Fieldless enums are simply a list of variants. This crate provides many features for fieldless enums which are difficult or impossible to provide for enums with data fields.

This crate contains a single item: the enhanced_enum! macro which generates an enum.

enhanced_enum::enhanced_enum!(YourEnum { A, B, C });

Translates to:

This example is not tested
pub enum YourEnum {

impl YourEnum {

/// Custom wrapper around an array of length `YourEnum::len()`.
/// This array can only be indexed by `YourEnum`.
pub struct YourEnumArray<T> {


  • Enhanced enums implement many common traits:

    • Debug, Display,
    • Copy, Clone,
    • PartialEq, Eq, PartialOrd, Ord,
    • Hash
  • Iterate through all variants of your enhanced enum with YourEnum::iter().

  • Count the number of variants with YourEnum::count() or YourEnum::len().

  • Make an array which can only be indexed by your enum. The enhanced_enum! macro generates a wrapper around a standard array, and this custom array type implements a very similar API to a standard array. The name of the new array type is the enum name with the word "Array" appended.

  • Convert between integers, strings, and enhanced enums.

    • YourEnum::try_from(usize) Also works with u32 and 64.
    • YourEnum::try_from(&str) Note that the string must exactly match a variant name, or else this returns an error.
    • your_enum as usize.
    • your_enum.to_string() -> String
    • your_enum.to_str() -> &'static str
  • Interface with Python via the pyo3 library. Currently this only implements a converting from python strings to rust. This is optionally compiled. To opt-in: build the enhanced_enum crate using the feature flag "pyo3".


A histogram for counting DNA nucleotides. This re-implements the example from the documentation for the Trait std::ops::Index.

enhanced_enum::enhanced_enum!(Nucleotide {

let nucleotide_count = NucleotideArray::<usize>::new_with(|x| match x {
    Nucleotide::A => 14,
    Nucleotide::C => 9,
    Nucleotide::G => 10,
    Nucleotide::T => 12
assert_eq!(nucleotide_count[Nucleotide::A], 14);
assert_eq!(nucleotide_count[Nucleotide::C], 9);
assert_eq!(nucleotide_count[Nucleotide::G], 10);
assert_eq!(nucleotide_count[Nucleotide::T], 12);



Define a new Enhanced Enum.