Is there a way to index an array by enums in Rust?

Viewed 9308

I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+

There is a known set of people, each of them owns some currency.

And I have the following enums:

enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}

I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by usize but by enum. E.g.:

data[Person::John][Currency::USD] = 100;

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

  • HashMap works on the heap (what makes it much slower than regular stack allocated array)

  • HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

3 Answers
Related