Course of Raku / Advanced / More about built-in types / Enumerations 🆕
Defining an enum
Declare an enum with the enum keyword, a name, and the
list of constant names:
enum Colour <red green blue>;This creates a new type, Colour, and three constants:
red, green, and blue. You can use
the constants directly by name:
say red; # red
say green; # greenBehind each name is a number, assigned automatically from zero in the
order you listed them — red is 0,
green is 1, blue is
2. Because the values are ordered, you can compare the
constants:
say red < blue; # TrueA variable can be typed with the enum, so that it accepts only those constants:
my Colour $c = green;
say $c; # greenIf a name might clash with something else in your program, you can
always refer to a constant through the enum’s name with
:::
say Colour::red; # redAn enum gives a set of related constants a name and a type, which makes code that uses them far clearer than bare numbers. The next topic looks at the numbers behind the names.
Practice
Complete the quiz that covers the contents of this topic.
Course navigation
← Enumerations 🆕 | Quiz — Enumerations →
💪 Or jump directly to the exercises in this
section.