Getting the "position"/index of an enum?

Say I have the following enum:

enum MyEnum {
	Foo,
	Bar,
	Baz
}

Given Enums don't really have a defined order per-se, is there a way to do the following pseudo-code?

let index = MyEnum::position_of(Bar);
// Index is now 1 (Or 2 depending on if it starts at 0 or not)

For non-data carrying enums, you can cast them to a numerical value.

#[derive(Copy, Clone)]
enum MyEnum {
    Foo,
    Bar
}

impl MyEnum {
    pub fn index(&self) -> usize {
        *self as usize
    }
}

fn main() {
    let e = MyEnum::Bar;
    dbg!(e.index()); // 1
    dbg!(MyEnum::Foo as usize); // 0
}
2 Likes

You can also derive PartialOrd, PartialEq, Ord, and Eq.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.