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:


#[derive(Debug, PartialEq)]
enum Color {

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:

is background red?  false
is background blue? true

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.


Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo