#does a Map for Enums exist?

15 messages · Page 1 of 1 (latest)

deft ferry
#
enum E {
  A,
  B,
  C,
}
type EnumMap<Enum: Sized, Value: Default>
fn main() {
  let mut map = EnumMap<E, f64>::default();
  map[E::B] = 2.0;
  assert_eq!(
    map as Vec,
    vec![
      (E::A, 0.0),
      (E::B, 2.0),
      (E::C, 0.0),
    ]
  );
}

does this hypothetical EnumMap type exist? or do i have to create it myself? and if i do have to create it myself, how to i do that?

#

does a Map for Enums exist?

dense onyxBOT
#

A JSON serialization file format

Version

1.0.87

Downloads

103 212 991

jaunty trout
#

That was the wrong crate, sorry

dense onyxBOT
#

A map with C-like enum keys represented internally as an array

Version

2.4.1

Downloads

1 808 330

jaunty trout
#

That's the one I was looking for. It's the closest I found at a glance

gilded imp
#

I would just make a method on the enum that does match and returns the "value" it represents

jaunty trout
#

I agree with that, I'd use an enum mapping in situations where the mapping values are dependent on runtime values

gilded imp
#
enum E {
    A,
    B,
    C,
}

impl E {
    fn value(&self) -> f64 {
        match self {
            E::A => 0.0,
            E::B => 2.0,
            E::C => 0.0,
        }
    }
}```
#

plus the compiler is going to optimize this a lot better than an entire hashmap

#

also if youre thinking about maybe doing this instead:rs match self { E::B => 2.0, _ => 0.0, }dont do that. you would lose out on the advantages of exhaustive pattern matching.
if you added a new variant to E, its nice to have the compiler just notify about every location where you need to also account for the change.

jaunty trout
#

I mean, one of the advantages of enum-map is that it doesn't do allocation - it uses an array

#

(And supports nesting of enums, enum Foo { A, B(bool) } becomes a length-3 array with distinct options for A, B(false), and B(true))

deft ferry
#

does the enum_map crate have a default feature?