Open In App

Rust – Enum

Improve
Improve
Like Article
Like
Save
Share
Report

An enum in Rust is a custom data type that represents data that can be anyone among several possible variants. Each variant in the enum can optionally have data associated with it. An enumerated type is defined using the enum keyword before the name of the enumeration. It also consists of methods.

Syntax:

enum name_of_enum{
variant_1,
variant_2,
.
.
variant_n
}

Here the name_of_enum is the name given to the Enum and variant_1, variant_2, …… variant_n are the values of the enumeration.

Example:

enum Month_name{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}

In the above example, Month_name is the name of enum, and January, February, March, April, May, June, July, August, September, October, November, December are values of an enum. A value of the enum can match any of the variants. For this reason, an enum is sometimes called a ‘sum type’: the set of possible values of the enum is the sum of the sets of possible values for each variant.

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

let jan = Month_name :: January;
let feb = Month_name :: February;
let mar = Month_name :: March;
let apr = Month_name :: April;
let may = Month_name :: May;
let jun = Month_name :: June;
let jul = Month_name :: July;
let aug = Month_name :: August;
let sep = Month_name :: September;
let oct = Month_name :: October;
let nov = Month_name :: November;
let dec = Month_name :: December;

Each variant of the enum has been namespaced under its identifier, and a double colon is used.

Let’s look at the code.

Rust




// The `derive` attribute automatically creates the implementation
// required to make this `enum` printable with `fmt::Debug`.
#[derive(Debug)]
  
enum Month_name {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
fn main() {
    let jan = Month_name :: January;
    let feb = Month_name :: February;
    let mar = Month_name :: March;
    let apr = Month_name :: April;
    let may = Month_name :: May;
    let jun = Month_name :: June;
    let jul = Month_name :: July;
    let aug = Month_name :: August;
    let sep = Month_name :: September;
    let oct = Month_name :: October;
    let nov = Month_name :: November;
    let dec = Month_name :: December;
  
   println!("{:?}",jan);
   println!("{:?}",feb);
   println!("{:?}",dec);
}


Output:

January
February
December

In the above example, Month_name is the name of the enumeration. Here jan, feb and dec are names of the month representing variations of the enum Month_name  for January, February, and December respectively.


Last Updated : 22 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads