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.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
The easiest way to convert an enum to a String in Rust is to implement the std::fmt::Display trait. Then you can call the to_string() method.
Additionally, creating a function that can take any type of Machine as its parameter is not possible using structs; in such a case, enums must be used. With an enum, the type of machine can be identified inside the function by using pattern matching with the match keyword.
All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.
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
If the enum is C-like (as in your example), then you can create a static
array of each of the variants and return an iterator of references to them:
use self::Direction::*; use std::slice::Iter; #[derive(Debug)] pub enum Direction { North, South, East, West, } impl Direction { pub fn iterator() -> Iter<'static, Direction> { static DIRECTIONS: [Direction; 4] = [North, South, East, West]; DIRECTIONS.iter() } } fn main() { for dir in Direction::iterator() { println!("{:?}", dir); } }
If you make the enum implement Copy
, you can use Iterator::copied
and return impl Trait
to have an iterator of values:
impl Direction { pub fn iterator() -> impl Iterator<Item = Direction> { [North, South, East, West].iter().copied() } }
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With