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

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


ljedrz provided a good solution.Another way to approach the problem is to use existing crate enum-map.

Add the following to your Cargo.toml:

[dependencies]enum-map = "*"enum-map-derive = "*"

Then, in src/main.rs:

extern crate enum_map;#[macro_use] extern crate enum_map_derive;#[derive(Debug, EnumMap)]enum Person { John, Tom, Nick }#[derive(Debug, EnumMap)]enum Currency { USD, EUR }use enum_map::EnumMap;use Person::*;use Currency::*;fn main() {    // Create 2D EnumMap populated with f64::default(), which is 0.0    let mut table : EnumMap<Person, EnumMap<Currency, f64>> = EnumMap::default();    table[John][EUR] = 15.25;    println!("table = {:?}", table);    println!("table[John][EUR] = {:?}", table[John][EUR]);}

The output:

table = EnumMap { array: [EnumMap { array: [0, 15.25] }, EnumMap { array: [0, 0] }, EnumMap { array: [0, 0] }] }table[John][EUR] = 15.25


If you need this to be implemented using arrays, this isn't as straightforward as it might seem.

In order to be able to contain both of these pieces of information in an array (to be able to index by them), you first need to combine them in a single type, e.g. in a struct:

struct Money([(Currency, usize); 2]);struct PersonFinances {    person: Person,    money: Money}

Then, if you want to be able to index the table, you will need to wrap it in your own type so that you can implement the Index trait for it:

use std::ops::Index;struct Table([PersonFinances; 3]);impl Index<(Person, Currency)> for Table {    type Output = usize;    fn index(&self, idx: (Person, Currency)) -> &Self::Output {        &self        .0        .iter()        .find(|&pf| pf.person == idx.0) // find the given Person        .expect("given Person not found!")        .money        .0        .iter()        .find(|&m| m.0 == idx.1)  // find the given Currency        .expect("given Currency not found!")        .1    }}

Then you can index the Table by a Person, Currency pair:

table[(Tom, EUR)]

Rust playground link to the whole code


You want a HashMap:

use std::collections::HashMap;#[derive(PartialEq, Eq, Hash)]enum Person {    John,    Tom,    Nick}#[derive(PartialEq, Eq, Hash)]enum Currency {    USD,    EUR}type Table = HashMap<Person, HashMap<Currency, f32>>;fn main() {    let mut table = Table::new();    let mut currency = HashMap::<Currency, f32>::new();    currency.insert(Currency::USD, 100_f32);    table.insert(Person::John, currency);    println!("{}", table[&Person::John][&Currency::USD]);}