Day 121 Enums In Rust

Now we know all the basics of Rust Programming Language like Control Flow Statements, Variables, Comments and Functions etc. Now we will be taking a look at intermediate concepts of Rust Programming Language. Things like Enums, Structs and Traits etc. For today we will try to understand what Enums are.

Enums

Enumerations or simply Enums allow us to define our own custom types. These data types consists of predefined named values called elements or members etc. To create an Enum in Rust we use the following syntax.

fn main() {
  // Creating an enum
  enum Name {
    Member01,
    Member02,
    // ...
    MemberN
  }
}

We use the enum keywork followed by the name of the enum and then curly braces and inside those curly braces comes the values or members.

Now lets create an enum named Fruits and see where can it be helpful.

fn main() {
  enum Fruit {
    Apple,
    Orange,
    Kiwi
  }
}

To reference an enum value we use double colon after the enum name and then the name of the value.

let apple = Fruit::Apple;

Members of the enums also have a value inside the enum. For example startig from zero the Kiwi fruit will have a value of 2.

println!("{}", Fruit::Kiwi as i32); // 2

But we can also define values to the elements of enums like so.

enum Company {
  Apple = "APL",
  Tesla = "TSLA"
}

This is all about Enums for now. This might be a simple thing for some but I still don't know where this thing could be useful in programming. Ofcourse this is useful in programming that is why it is there. But maybe I will come across something that will let me know the importance of enums in programming but for now lets just leave it like this.


zainscizainsci