State Machines

1

enum and match: Stop Encoding State as Bare Integers

5 minute

C often represents state with integers:

#define STATE_IDLE      0
#define STATE_READING   1
#define STATE_ERROR     2

Or with enum:

enum State {
    STATE_IDLE,
    STATE_READING,
    STATE_ERROR,
};

This is much clearer than bare numbers, but state is often more than a name. Different states may need different data. C code commonly puts a state code and many fields into one struct, then relies on convention to know which fields are valid.

Rust enum is closer to “a type that can be exactly one of several shapes,” and each shape can carry its own data.

Read More