Javatpoint Logo
Javatpoint Logo

What is Rust Enum?

Enum is a custom data type which contains some definite values. It is defined with an enum keyword before the name of the enumeration. It also consists of methods.

The syntax of enum:

In the above syntax, enum_name is the name of the enum and variant1,variant2,.. are the enum values related to the enum name.

For example:

In the above example, computer_language is the enum name and C, C++, Java are the values of computer_language.

Enum values

Let's create the instance of each of the variants. It looks like:

In the above scenario, we create the three instances, i.e., c, cplus, java containing the values C, C++, Java respectively. Each variant of enum has been namespaced under its identifier, and double colon is used. This is useful because Computer_language::C, Computer_language::C++, Computer_language::Java belongs to the same type, i.e., Computer_language.

  • We can also define a function on a particular instance. Let's define the function that takes the instance of type Computer_language; then it looks like:

This function can be called by either of any variant:

Let's understand through an example.


Name("Hema") s Id(2) b Profile("Computer Engineer")

In the above example, Employee is a custom data type which contains three variants such as Name(String), Id(i32), Profile(String). The ":?" is used to print the instance of each variant.

Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials