Crate enum_derive [] [src]

This crate provides several macros for deriving some useful methods for unitary enums (i.e. enums where variants do not have payloads).

All of these macros are designed to be used with the custom_derive crate, though they can be used independent of it.

Note: see also the TryFrom! macro provided by the conv crate to derive a function for creating enum values from integer values.

Example

Derive iterators that yield all variants of an enum.

#[macro_use] extern crate custom_derive;
#[macro_use] extern crate enum_derive;

custom_derive! {
    #[derive(Debug, PartialEq, Eq,
        IterVariants(CandyVariants), IterVariantNames(CandyVariantNames))]
    pub enum Candy { Musk, FruitRock, BoPeeps, LemonSherbert }
}

let vars: CandyVariants = Candy::iter_variants();
let names: CandyVariantNames = Candy::iter_variant_names();
assert_eq!(&*vars.zip(names).collect::<Vec<_>>(), &[
    (Candy::Musk, "Musk"),
    (Candy::FruitRock, "FruitRock"),
    (Candy::BoPeeps, "BoPeeps"),
    (Candy::LemonSherbert, "LemonSherbert"),
]);

Overview

This crate provides macros to derive the following methods for unitary variant enums:

  • IterVariants derives iter_variants(), which returns an iterator over the variants of the enum in lexical order.
  • IterVariantNames derives iter_variant_names(), which returns an iterator over the string names of the variants of the enum in lexical order.

Both of these accept a single deriving form. Taking IterVariants as an example, it must be invoked like so:

custom_derive! {
    #[derive(IterVariants(GetVariants))]
    pub enum Get { Up, Down, AllAround }
}

The argument is the name of the iterator type that will be generated. Neither macro imposes any naming requirements, save the obvious: the name must not conflict with any other types.

The methods and iterator types generated will be public if the enum itself is public; otherwise, they will be private.

Using Without custom_derive!

Although designed to be used with custom_derive!, all of the macros in this crate can be used without it. The following:

custom_derive! {
    #[derive(Copy, Clone, Debug, IterVariants(Vars))]
    enum ItAintRight { BabeNo, NoNo, BoyBoy }
}

Can also be written as:

#[derive(Copy, Clone, Debug)]
enum ItAintRight { BabeNo, NoNo, BoyBoy }

IterVariants! { (Vars) enum ItAintRight { BabeNo, NoNo, BoyBoy } }

Macros

IterVariantNames!
IterVariants!