Enum(Enumerator Operator) in Rust

In Rust Enum which is an enumerator operator is used to declare a custom data type which can hold more than one fixed value. The fixed values are called variants of the enumerator. The enumerator data type is declared by the keyword enum.

Enum is used to define data which comes under a single category. For example, in the list of fruits, we may have apples, mangoes, lichi, etc. So, to get the data directly from the fruit category, we can directly refer to the fruit (let us say the enum data type)and retrieve the data.

Enum data type can be declared using the keyword enum, and the values of the enum reside inside the two braces, { }, which marks the start and end of the enum.

Syntax for Enum

enum enum_name {
   // value1,
   // value2,
   ...................
   ...................
    //value3
}

Program to print the name of fruits using an enum.

#
[derive(Debug)]
enum Fruits {
 Apple,
 Mango
}
fn main() {
 let apple = Fruits::Apple;
 let mango = Fruits::Mango;

 println!("{:?}", apple);
 println!("{:?}", mango);
}

As shown in the above program, we have declared an Enum using the keyword enum , followed by the enum name Fruit.

After the opening braces { , we have declared the values- Apple, Mango and closed the enum with the closing parenthesis }.

Inside the main() function, we have declared an instance- apple and assigned it with the Enum value- Apple. Similarly, we have assigned the second instance-mango .

Then we printed the instances directly using the macro println!() and using :? inside the delimiter.

Program Output :

rust-enum

Use of Enum with Structure

Enum is mainly used for categorizing a particular attribute. So, as we know that a structure contains several attributes inside it, therefore enum can be used to categorize any one or all the attributes of a structure.

A program with an example will make things much more clear.

#
[derive(Debug)]
enum Result {
 Pass,
 Fail
}# [derive(Debug)]
struct Student {
 name: String,
 result: Result
}
fn main() {
 let student1 = Student {
  name: String::from("John"),
  result: Result::Pass
 };
 let student2 = Student {
  name: String::from("Riya"),
  result: Result::Fail
 };
 println!("{:?}", student1);
 println!("{:?}", student2);
}

In this program, we have declared an enum called Result. Inside, the enum Result, we have two variants- Point our Mistakes and Post Your Suggestions