29

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.

0

1 Answer 1

55

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);
}
4
  • 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
    Commented Oct 26, 2015 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
    Commented Jan 22, 2018 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
    Commented Jan 22, 2018 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<PieceType>, 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
    Commented Jan 22, 2018 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.