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

rust enum
rust enum
rust strum
rust int to enum
rust impl enum
rust some enum
rust enum to string
rust enum values

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 turn with the enhanced for loop like:

for(Direction dir : Direction.values())  {
    //do something with dir
}

I would like to do a similar thing with Rust enums.

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<T> {
    None,
    Some(T)
}

?

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

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.

wtaf, to the potential complexity of enum values, but what would be the most idiomatic way, given a simple enumeration enum Foo { Bar, Baz, Zoo } to create an iterator over all the values? I decided to have some fun and rewrote it all in Rust! I'm writing code to initialize a deck with 52 cards and shuffle them. In Java, I use an ArrayList and iterate through the Suit enum and the Rank enum, adding a Card(suit,rank) object as I go along.

Iterating over static enum values : rust, Trait to iterate over the variants of a field-less enum. Derive Macros. IntoEnumIterator. Derives IntoEnumIterator for field-less enums. Iterating over static enum values I know that this isn't something that is supported automatically due to the potential complexity of enum values, but what would be the most idiomatic way, given a simple enumeration enum Foo { Bar, Baz, Zoo } to create an iterator over all the values?

You can use the strum crate to easily iterate through the values of an enum.

use strum::IntoEnumIterator; // 0.17.1
use strum_macros::EnumIter; // 0.17.1

#[derive(Debug, EnumIter)]
enum Direction {
    NORTH,
    SOUTH,
    EAST,
    WEST,
}

fn main() {
    for direction in Direction::iter() {
        println!("{:?}", direction);
    }
}

Output:

NORTH
SOUTH
EAST
WEST

enum_iterator - Rust, I have an enum where it'd be nice to be able to iterate over all the static elements of Is there a current best practices for providing an iterator… After parsing, the options are stored as a vector of enum (with additional data). We need to easily check for an option, and if it is there, access the data. The c way would be an array of struct containing an enum and a void*. The function to check for an option would get one enum value and return the void ptr, or NULL.

I implemented basic functionality in the crate plain_enum.

It can be used to declare a C-like enum as follows:

#[macro_use]
extern crate plain_enum;

plain_enum_mod!(module_for_enum, EnumName {
    EnumVal1,
    EnumVal2,
    EnumVal3,
});

And will then allow you to do things like the following:

for value in EnumName::values() {
    // do things with value
}

let enummap = EnumName::map_from_fn(|value| {
    convert_enum_value_to_mapped_value(value)
})

Implementing Iter for enums - help, I have an enum like pub enum StackValue { Value(f64), Values(Vec<f64>) } If I have a slice If I have a slice of these enums is it possible to iterate through that slice or is loop through and performing a match the only way ? The for in construct can be used to iterate through an Iterator. One of the easiest ways to create an iterator is to use the range notation a..b. This yields values from a (inclusive) to b (exclusive) in steps of one. Let's write FizzBuzz using for instead of while.

Iterate a slice of enum variants - help, In fact, it seems like if this was implemented in such a way that built-in types could be iterated over as well, then all 512 possible values of my� There are two syntactic forms for creating an array: A list with each element, i.e., [x, y, z]. A repeat expression [x; N], which produces an array with N copies of x. The type of x must be Copy. Arrays of sizes from 0 to 32 (inclusive) implement the following traits if the element type allows it: Debug; IntoIterator (implemented for &[T; N

RFC: Enum trait � Issue #284 � rust-lang/rfcs � GitHub, One way I could implement this is by manually naming every variant of It's essentially the dual of syn as it will make serializing rust code really easy. I want to be able to iterate through enum variants, something like this: #! The OpenAPI standard specifies keys and specific values for its json or yaml files. That can be deserialized by serde. But it also allows any key name which starts with "x-" , for instance "x-myextension" to be added to the document, their names and contents (inside you can have an object with more keys) are arbitrary.

Creating an enum iterator using Macros 1.1 – Christopher Breeden , Idiom #7 Iterate over list indexes and values. Print each index i with its value x from an array-like collection items. Dart � Dart � Ada � C � Caml � Clojure � C++ � C++� The return values from f will end up in the Vec in the order they have been generated. If new_len is less than len, the Vec is simply truncated. This method uses a closure to create new values on every push. If you'd rather Clone a given value, use resize.

Comments
  • There's an issue about an Enum trait which would possibly be able to be derived to give something like for dir in Direction::values() { ... } (maybe).
  • This is helpful. I think the easiest thing for me to do is maybe write an impl of my enum that returns a list of the values or an iterator or something. Thanks!
  • I respectfully disagree that enumerated enums are not worth it. That this is a common and useful thing to do is why they are called enums! The algebraic power is great to have, of course, but convenience for the most common case is good too.
  • @RexKerr, that was just my suggestion about the reasons why this feature is still not there. Halted discussion in the corresponding issue supports my point, I believe. BTW, when I needed to do something with all enum elements at once, it usually was some kind of index (e.g. hash map) which allowed to retrieve enum value by some key, and this index should be constructed manually anyway.
  • @VladimirMatveev - Eh, very little should be constructed manually which can be constructed automatically. Kind of the point of having compilers, no? But I agree with your analysis.
  • This actually seems to probably be a better option than to use "enum" from rust for your needs. I actually wonder if ruts would have been better off calling their enums, unions or something else. Also, as a powerful variant, you can associate additional information like: [North(0), South(180), EAST(90), WEST(270)], etc, or more given the tuple help...