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
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- {
[North, South, East, West].iter().copied()
}
}
See also: