Home > Software design >  Iterate over type of enum parameter
Iterate over type of enum parameter

Time:06-15

Is it possible to define a function, which takes any enum value as parameter and then iterates over the type? Something like this pseudo code:

#[derive(Display)]
enum Difficulty {
    Easy,
    Middle,
    Hard,
}

fn enum_as_radio_select<T: Enum   Display>(selected: T) {
    for enum_value in T::iter() {
        let is_selected = enum_value == selected;
        let text = enum_value.to_string();
        add_radio_button(is_selected, text);
    }
}

enum_as_radio_select(Difficulty::Easy);

CodePudding user response:

The strum crate has this: #[derive(EnumIter)] (note you need to activate the derive feature):

#[derive(strum::EnumIter, Display, PartialEq, Eq)]
enum Difficulty {
    Easy,
    Middle,
    Hard,
}

fn enum_as_radio_select<T: Display   strum::IntoEnumIterator   PartialEq>(selected: T) {
    for enum_value in T::iter() {
        let is_selected = enum_value == selected;
        let text = enum_value.to_string();
        add_radio_button(is_selected, text);
    }
}

enum_as_radio_select(Difficulty::Easy);
  • Related