Rust Lang

Rust Enums

In this article, we will learn about enumerations, or enums for short. Enums allow us to define a custom type consisting of variants. They are closely similar to a struct and each valid struct is a valid enum.

Rust Declare Enum

We can define an enum in Rust using the enum keyword, followed by the name of the enum. We then create the enum body inside a pair of curly braces.

The enum body is made up of possible variants separated by commas.

The syntax is as shown:

enumenum_name {
    variant(),
    variant2
    variant3
    …
}

The rust recommends to use UpperCamelCasing for naming enum variants.

Let us take a case where enums can be useful. An example that comes to mind are types of charge. There are two types of charge:

  1. Negative
  2. Positive

Since there can only be one type of charge at a given time, it makes sense to use an enum. An example is as shown below:

enumCharge {
    Negative,
    Positive
}

Rust Initialize Enum

Once we have defined an enum, we can create instances of each of the variants. An example is as shown:

fnmain() {
let p = Charge::Positive;
let n = Charge::Negative;
}

Using Enums with Structs

One way to expand an enum is to combine it with a struct. Consider the example code below:

structElement {
name: String,
    value: i32,
    charge: Charge,
}

Once we have a struct, we can create an instance of the struct and pass the properties of the enum as shown in the example below:

enum Charge {
    Negative,
    Positive
}
struct Element {
    name: String,
    value: i32,
    charge: Charge,
}
fn main() {
    let elem1 = Element {
        name: "Sodium".to_string(),
        value: 1,
        charge: Charge::Positive
    };
    let elem2 = Element {
        name: "Chloride".to_string(),
        value: 1,
        charge: Charge::Negative
    };
}

In the example code above, we define two instances of the Element struct. We then pass the charge property as a value from the Charge enum.

Rust Derive Trait

If you attempt to print the instances of the struct above, the compiler will return an error. To print the struct, we need to “import” the Debug trait.

This is done using the derive attribute. This allow us to get various trait implementations such as:

  1. Debug trait
  2. Eq, PartialEq, Ord, PartialOrd
  3. Hash trait,
  4. Default trait
  5. Etc.

The syntax to derive a trait is as shown:

#[derive(trait_name)]

Since we need to print the struct to the console, we can derive the Debug trait as shown:

#[derive(Debug)]
enumCharge {
    Negative,
    Positive
}
#[derive(Debug)]
structElement {
    name: String,
    value: i32,
    charge: Charge,
}

We can then use this trait to print the struct to the console as:

println!("{:#?}", elem1);

This should print the struct to the console as:

You can check the derive documentation in the resource provided below:

https://doc.rust-lang.org/reference/attributes/derive.html

Conclusion

In this article, we explored how to create, use and work with enum types in Rust. We also covered how to use enums with structs and how to derive traits.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list