Enums

Representations of enumerations.

C++

Rust

Java


enum basic_enum {
  option1 = 1,
  option2
};

enum class char_enum : char {
  optiona = 'a',
  optionb
};

basic_enum e1 = option1;
char_enum e2 = char_enum::optiona;

if(e1 == option2)
  e2 = char_enum::optionb;

if(e2 == char_enum::optionb)
  e1 = option2;



#[derive(PartialEq, Eq)]
enum BasicEnum {
    Option1 = 1,
    Option2
}

enum CharEnum {
    OptionA(char),
    OptionB(char)
}

let mut e1 = BasicEnum::Option1;
let mut e2 = CharEnum::OptionA('a');

if e1 == BasicEnum::Option2 {
    e2 = CharEnum::OptionB('b');
}

match e2 {
    CharEnum::OptionB(..) => e1 = BasicEnum::Option2,
    _ => {}
}


enum BasicEnum {
  Option1,
  Option2
}

enum CharEnum {
  OptionA('a'),
  OptionB('b');

  private char v;

  CharEnum(char v) {
    this.v = v;
  }
}

public static void main(String[] args) {
  BasicEnum e1 = BasicEnum.Option1;
  CharEnum e2 = CharEnum.OptionA;

  if(e1.equals(BasicEnum.Option2))
    e2 = CharEnum.OptionB;

  if(e2.equals(CharEnum.OptionB))
    e1 = BasicEnum.Option2;
}



C++ has two methods to represent an enum. Using enum class should be favored as it provides scoping.

Rust's enums provides equality testing by adding #[derive(PartialEq, Eq)] to the enum. The use of match is helpful because it forces the checking of all options of the enum. Rust also provides a mechanism to capture an instance of a type for an option of an enum.

Java's enum is similar to C++ although you can define methods and a constructor.