Enumerate and match in Rust

enumerate enum match dead_code Debug PartialEq

The enum keyword in Rust allows us to enumerate a number of values and then differentiate among them. E.g. The days of the week, the months of the year, distinct colors, etc.

Once you defined an enum you can assign the individual values of the enum to variables and then you can compare the variable to the possible values of the enum.

There are two major ways to compare the values. One of them is dircetly using the == operator. In this case we compare to a specific individual value.

The other option is to use a match where the "arms" of the match must cover all the possibilities as you can see in the following example:

examples/enumerate_and_match.rs

#[derive(Debug, PartialEq)]
#[allow(dead_code)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let background = Color::Blue;
    let foreground = Color::Red;
    println!("{:?}", background);
    println!("{:?}", foreground);

    println!("is background red?  {}", background == Color::Red);
    println!("is background blue? {}", background == Color::Blue);

    for clr in [foreground, background] {
        match clr {
            Color::Red => println!("red"),
            Color::Green => println!("green"),
            Color::Blue => println!("blue"),
        }
    }
}

The output of the above code is:

Blue
Red
is background red?  false
is background blue? true
red
blue

More about enums

Read the defining enums part of the Rust book, see the Enums part of the Rust by example, or read the documentatin on enum.