Implementing Iter for enums


#1

I have an enum where it’d be nice to be able to iterate over all the static elements of the enum. I found an old Reddit thread about this, but it’s 2 years old. Is there a current best practices for providing an iterator for an enum, either through a macro or manually?

On a related note, I’d like to expand this enum so that it differs by platform. I’d like to do that but I wanted to check if that’s considered a bad practice by the Rust community.


#2

I used such code (you can easy adopt it to generate iterators):

macro_rules! define_enum {
    ($Name:ident { $($Variant:ident),* $(,)* }) =>
    {
        #[derive(Debug)]
        pub enum $Name {
            $($Variant),*,
        }
        const ENUM_ITEMS: &'static [$Name] = &[$($Name::$Variant),*];        
    }
}

define_enum!(TestEnum {
    Foo,
    Boo,
});


fn main() {
    for i in ENUM_ITEMS {
        println!("{:?}", *i);
    }
}

#3

I wrote a blog post on how you could do this using procedural macros: https://cbreeden.github.io/Macros11/