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- Pass and Fail. Now, these two values can be used to assign the attribute result of the structure Student.

We have created two instances of the structure Student- student1 and student2. The field name result in the first instance initialization are name and result . The attribute name is assigned directly a data which is of string datatype. But the, the second attribute- result is assigned data via the enum Result.

result: Result::Pass

Now, when we shall create a different instance of the structure Student, we can assign the field result with a different value from the enum. Thus we can categorize an attribute with the variants of the Enumerator.

Program Output :

rust-enum-with-structure

Option Enum

In Rust, Option is an in-built enum. This enum can have only two variants Some and None. A function can use the Option enum in such a way that, if the function returns a value then the Some variant with the data will be displayed. Otherwise, if the function does not return any value, Null, will be displayed.

Note : There is nothing called Null, in Rust, therefore the keyword None is used to indicate Null.

Syntax for Option Enum

enum Option<data-type> {
   Some(data),        //used to return a value.
   None                  // indicate no return of values.
   }

A program to check whether a number is greater than 5.

fn main() {
 let result = check(30);
 println!("{:?}", result);
}
fn check(number: i32) -> Option < bool > {
 if number > 5 {
  Some(true)
 } else {

  None
 }
}

In the above Program, we have created a function check() which accepts an i32 type parameter. And the return type of the function is an Option enumerator. (Option enum), which returns a bool data-type. It means, that either the value can be true or false.

Now inside the Option enum, we have an if statement to check whether the number is less than or greater than 5. If the decision is true(when the number is greater then 5), the data of the Some variant is returned. Otherwise, if the decision is not true (when the number is not greater then 5), then the None is returned.

Now, inside the function main() we have declared a variable called result, which stores value returned by the function check() . Now we simply pass a value (30 in our case) and prints the value of result using the macro println!().

Program Output(when the decision is true- number is greater than 5)

rust-enum-option-true

Now let us see how the variant None is returned when the decision is not true.

Program : (When number is not greater than 5)

fn main() {
 let result = check(2);
 println!("{:?}", result);
}
fn check(number: i32) -> Option < bool > {
 if number > 5 {
  Some(true)
 } else {

  None
 }
}

Program Output(when the decision is false- number is not greater than 5)

rust-enum-option-not-true

Enum with Match operator

Enum and its variants can be used with match operator to match a particular name or keyword and execute a statement or set of statements.

For this, we need to pass the enum name to a user-defined function as a parameter and inside that function we can use the match operator to perform a particular task when a specific variant name is matched. To be more clear, let us consider an example:

Suppose we have a category called- fruit. And there are three different kinds of fruits-Apple, Mango and Strawberry. We want to write a program using enum and match operator, so that, we get details of each fruit, when a particular fruit category is selected (or matches).

Syntax for match operator :

fn an_user_defined_function(parameter: Enum_name) {
 match parameter {
  EnumName::Variant1 => {
    //Some code
   },
   EnumName::Variant2 => {
    //some code
   }
 }
}

Program to print the taste of three different fruits :

enum FruitName {
 Apple,
 Orange,
 Strawberry
}
fn fruitdetails(fruit: FruitName) {
 match fruit {
  FruitName::Apple => {
    println!("Apple is a red-orange colour fruit and its really tasty");
   },
   FruitName::Orange => {
    println!("Orange is a orange colour fruit, and its tasts sour and sweet too. ");
   },
   FruitName::Strawberry => {
    println!("Strawberry is my favourite fruit");
   }
 }
}
fn main() {
 fruitdetails(FruitName::Apple);
 fruitdetails(FruitName::Orange);
 fruitdetails(FruitName::Strawberry);
}

In the program above, we have an enum FruitName. Inside it, we have names of three different fruits which are out variants. We have created an user-defined function called- fruitdetails(). Inside the function fruitdetails(), we have parameter value- fruit which is of enum type(Fruit Name).

Inside the function, we have declared the match operator followed by the local variable-fruit. Now, enum name is matched with the enum value, and depending on that, a certain block of code gets executed. (the macro println!(), in our case to print details of the specific fruit.)

Next, inside the main() function, we simply pass the Enum_Name along with the variants inside the user-defined function to print the details of each variant.

Program Output :

rust-enum-match

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions