Enums in Rust

Enumerated types (enums) are a special case of sum types. An enum is a type that has a fixed number of possible values, each with a distinct name.

Rust has a dedicated enum type as a distinct language feature, which makes it straightforward to define and work with enums.

Our enum type ServerState is defined in a straightforward manner.

enum ServerState {
    Idle,
    Connected,
    Error,
    Retrying,
}

To print out the values of ServerState, we implement the fmt::Display trait.

use std::fmt;

impl fmt::Display for ServerState {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let state_name = match self {
            ServerState::Idle => "idle",
            ServerState::Connected => "connected",
            ServerState::Error => "error",
            ServerState::Retrying => "retrying",
        };
        write!(f, "{}", state_name)
    }
}

By implementing the fmt::Display trait, values of ServerState can be printed out or converted to strings. This can get cumbersome if there are many possible values.

Here’s the main function, which demonstrates using the ServerState enum and the transition function.

fn main() {
    let ns = transition(ServerState::Idle);
    println!("{}", ns);

    let ns2 = transition(ns);
    println!("{}", ns2);
}

transition emulates a state transition for a server; it takes the existing state and returns a new state.

fn transition(s: ServerState) -> ServerState {
    match s {
        ServerState::Idle => ServerState::Connected,
        ServerState::Connected | ServerState::Retrying => {
            // Suppose we check some predicates here to determine the next state…
            ServerState::Idle
        }
        ServerState::Error => ServerState::Error,
        _ => panic!("unknown state: {}", s),
    }
}

To run the program, put the code in main.rs and use cargo run.

$ cargo run
connected
idle

Enums in Rust have many useful features, including associated functions and pattern matching. Let’s explore more about the language to leverage these features.