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

前端 未结 5 2045
春和景丽
春和景丽 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条回答
  •  Happy的楠姐
    2020-12-08 04:26

    No, there is none. I think that is because enums in Rust are much more powerful than in Java - they are in fact full-fledged algebraic data types. For example, how would you expect to iterate over values of this enum:

    enum Option {
        None,
        Some(T)
    }
    

    ?

    Its second member, Some, is not a static constant - you use it to create values of Option:

    let x = Some(1);
    let y = Some("abc");
    

    So there is no sane way you can iterate over values of any enum.

    Of course, I think, it would be possible to add special support for static enums (i.e. enums with only static items) into the compiler, so it would generate some function which return values of the enum or a static vector with them, but I believe that additional complexity in the compiler is just not worth it.

    If you really want this functionality, you could write a custom syntax extension (see this issue). This extension should receive a list of identifiers and output an enum and a static constant vector with these identifiers as a content. A regular macro would also work to some extent, but as far as I remember you cannot transcript macro arguments with multiplicity twice, so you'll have to write enum elements twice manually, which is not convenient.

    Also this issue may be of some interest: #5417

    And of course you can always write code which returns a list of enum elements by hand.

提交回复
热议问题