enum

An enum declaration inside a lib declares a C enum:

  1. lib X
  2. # In C:
  3. #
  4. # enum SomeEnum {
  5. # Zero,
  6. # One,
  7. # Two,
  8. # Three,
  9. # };
  10. enum SomeEnum
  11. Zero
  12. One
  13. Two
  14. Three
  15. end
  16. end

As in C, the first member of the enum has a value of zero and each successive value is incremented by one.

To use a value:

  1. X::SomeEnum::One # => One

You can specify the value of a member:

  1. lib X
  2. enum SomeEnum
  3. Ten = 10
  4. Twenty = 10 * 2
  5. ThirtyTwo = 1 << 5
  6. end
  7. end

As you can see, some basic math is allowed for a member value: +, -, *, /, &, |, <<, >> and %.

The type of an enum member is Int32 by default, even if you specify a different type in a constant value:

  1. lib X
  2. enum SomeEnum
  3. A = 1_u32
  4. end
  5. end
  6. X::SomeEnum # => 1_i32

However, you can change this default type:

  1. lib X
  2. enum SomeEnum : Int8
  3. Zero
  4. Two = 2
  5. end
  6. end
  7. X::SomeEnum::Zero # => 0_i8
  8. X::SomeEnum::Two # => 2_i8

You can use an enum as a type in a fun parameter or struct or union members:

  1. lib X
  2. enum SomeEnum
  3. One
  4. Two
  5. end
  6. fun some_fun(value : SomeEnum)
  7. end