Industrial Training




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:


 enum enum_name  
{  
  variant1,  
 variant2,  
.  
.  
}  

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:


enum Computer_language  
  
  C,  
  C++,  
  Java,  
   

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:


 let c = Computer_language :: C;  
let cplus = Computer_language :: C++;  
let java = Computer_language :: Java;

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:

fn language_type(language_name::Computer_language);  

This function can be called by either of any variant:


language_type(Computer_language :: C++);  

Let's understand through an example.
 #[derive(Debug)]  
enum Employee {  
    Name(String),  
    Id(i32),  
    Profile(String),  
}  
fn main() {  
      
    let n = Employee::Name("Hema".to_string());  
    let i = Employee::Id(2);  
    let p = Employee::Profile("Computer Engineer".to_string());  
    println!(" {:?} s {:?} b {:?}", n,i,p);  
}  

Output:
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.




Hi I am Pluto.