Auto generating to_enum

Suppose we have:

pub enum  Animal {
  Cat = 0,
  Dog = 1,
  Horse = 2,
}

impl Animal {
  fn from_u8(x: u8) -> Option<Animal> {
    match x {
      0 => Some(Animal::Cat),
      1 => Some(Animal::Dog),
      2 => Some(Animal::Horse),
      _ => None
    }
  }
}

Is there anyway to auto generate the from_u8 function? (to avoid duplication / silly errors)

There are some crates like strum that provide macros.

I often reach for FromPrimitive and ToPrimitive from num-derive in these situations.

You can also just generate your enum from a macro, giving you something like this:

fieldless_enum!{
    Animal as u8 {
        Cat = 0,
        Dog = 1,
        Horse = 2,
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a675cc552bd9af8b10e59f304fd2fa46

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.