In Rust, is there a way to iterate through the values of an enum?

前端 未结 5 2044
春和景丽
春和景丽 2020-12-08 03:52

I come from a Java background and I might have something like enum Direction { NORTH, SOUTH, EAST, WEST} and I could do something with each of the values in tur

5条回答
  •  感情败类
    2020-12-08 04:16

    If you do not want to import a third-party crate, you can make your own macro to do so. Here is how I achieved it (there are probably ways to improve this):

    macro_rules! iterable_enum {
        ($visibility:vis, $name:ident, $($member:tt),*) => {
            $visibility enum $name {$($member),*}
            impl $name {
                fn iterate() -> Vec<$name> {
                    vec![$($name::$member,)*]
                }
            }
        };
        ($name:ident, $($member:tt),*) => {
            iterable_enum!(, $name, $($member),*)
        };
    }
    

    And then you can do:

    iterable_enum!(pub, EnumName, Value1, Value2, Value3);
    
    fn main() {
        for member in EnumName::iterate() {
            // ...
        }
    }
    

    This implementation is limited to simple enums. Consider the following enum, how would you iterate over it?:

    enum MoreComplexEnum {
        One(T1),
        Two(T2),
        Other,
        Both(T1, T2),
        Error(String),
    }
    

    Because of the power of enums in Rust, it can be difficult to implement a perfectly iterable enum, since they are not like the simple enums you have in C or Java.

提交回复
热议问题