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.
To print out the values of ServerState
, we implement the fmt::Display
trait.
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.
transition
emulates a state transition for a server; it takes the existing state and returns a new state.
To run the program, put the code in main.rs
and use cargo run
.
Enums in Rust have many useful features, including associated functions and pattern matching. Let’s explore more about the language to leverage these features.