28

It is possible to write constructions like this:

enum Number {
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4,
}

but for what purpose? I can't find any method to get the value of an enum variant.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Gedweb
  • 697
  • 1
  • 6
  • 22

1 Answers1

50

You get the value by casting the enum variant to an integral type:

enum Thing {
    A = 1,
    B = 2,
}

fn main() {
    println!("{}", Thing::A as u8);
    println!("{}", Thing::B as u8);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    @ArtemGr great point! Bitflags and integral enumerations have some implementation overlap but are usually pretty different conceptually, so it's good to know about both. – Shepmaster Oct 26 '15 at 19:43
  • 1
    @Shepmaster Is there a more universal way to handle this, so that one does not need to make a cast at every arithmetic operation performed with an enum type? – tinker Jan 22 '18 at 21:59
  • 2
    @tinker no, there's not. Rust enums are not just pretty names for integer constants; you shouldn't be performing arithmetic on them frequently. – Shepmaster Jan 22 '18 at 22:05
  • @tinker It seems like you should have a `struct Piece(u8)` which is the packed form, and two enums `PieceType { A, B, C }` and `Color { Red, White }`. The `Piece` constructor would take in an `Option, Color` and `Piece` would have methods to convert to and from the packed form. Your `Piece` could even use the bitflags mentioned in a comment above. – Shepmaster Jan 22 '18 at 22:11