Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enums: Illegal States, Unrepresentable

A struct that accumulated one flag at a time:

pub struct Connection {
    pub connected: bool,
    pub connecting: bool,
    pub addr: Option<SocketAddr>,   // Some iff connected?
    pub retry_count: Option<u32>,   // Some iff connecting?
    pub error: Option<String>,
}

Five fields allow 32 combinations, of which perhaps 4 mean anything. Every function that touches this struct must handle, or mishandle unnoticed, the other 28.

The same states as an enum:

pub enum Connection {
    Disconnected,
    Connecting { retry_count: u32 },
    Connected { addr: SocketAddr },
    Failed { error: ConnectError },
}

The 28 meaningless states can no longer be written down. And as long as matches avoid _ arms, adding a Draining variant later produces a compile error everywhere it’s not handled.

In review, count the bools and Options in a generated struct and ask whether they are independent or one state machine spread across fields. If combinations of them are meaningless, the fix is an enum whose variants carry their own data.