The enum type in D language is used to define named constants which can be referred to by a collective name.
The keyword enum
is used to declare an enumeration list as a type of enum.
enum nameOf_enum {
enumeration list
}
enum
keyword indicates that the set of data is of type enum.nameOf_enum
parameter in the syntax is the identifier for the enumeration list. When an enumeration list is declared without the nameOf_enum
being provided, the enum
is automatically given a type of int.We can access the members of an enumeration list by writing the name of the enum followed by a dot and then the name of the member of interest. The index can be returned using a formatter print and the formatted set to an integer. See the example below:
import std.stdio;enum Users { students, teachers, admins, executives};int main() {Users personnel;personnel= Users.students;writefln("Frequent Users: %s", personnel);writefln("Executives index: %d", Users.executives);return 0;}
The 0
in the output of the code above is the index and value of tall
in the height
enum relative to the size or length of the enum
. We can also see how the member tall
is referenced in the formatted printing method writefln
in line 6.
Let’s look at the code below:
import std.stdio;enum Users { students, teachers, admins, executives};int main() {Users personnel;personnel= Users.students;writefln("Frequent Users: %s", personnel);writefln("Executives index: %d", Users.executives);return 0;}
enum
Users
and give some members.main()
, which returns a value.personnel
is declared as a data type of the enum Users
.student
from the Users
enum.Note: Enumeration lists have a default value of their position index value, they can also be assigned values like below:
enum alphas{x =4,y = 6,z = 12}