What is enum in D Language?

Overview

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.

Syntax

enum nameOf_enum {  
   enumeration list 
}
  • In the general syntax structure shown above, the enum keyword indicates that the set of data is of type enum.
  • The 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:

Example

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.

Code

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;
}

Explanation

  • Line 3: We define the enum Usersand give some members.
  • Line 5: We start the function block main(), which returns a value.
  • Line 6: We show where the variable personnel is declared as a data type of the enum Users.
  • Line 8: We have the value of student from the Users enum.
  • Lines 9 and 10: We print the results.

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}

Free Resources