Enums in Nim

Our enum type ServerState has an underlying int type.

The possible values for ServerState are defined as constants in an enum. In Nim, the enums automatically get successive integer values starting from 0.

By implementing the toString method, values of ServerState can be printed out or converted to strings.

type
  ServerState = enum
    StateIdle, StateConnected, StateError, StateRetrying

var stateName = initTable[ServerState, string](
  {
    StateIdle: "idle",
    StateConnected: "connected",
    StateError: "error",
    StateRetrying: "retrying"
  }
)

proc toString(ss: ServerState): string =
  return stateName[ss]

proc transition(s: ServerState): ServerState =
  case s
  of StateIdle:
    return StateConnected
  of StateConnected, StateRetrying:
    return StateIdle
  of StateError:
    return StateError
  else:
    raise newException(ValueError, "unknown state: " & $s)

proc main() =
  let ns = transition(StateIdle)
  echo toString(ns)

  let ns2 = transition(ns)
  echo toString(ns2)

main()

To run the program, put the code in enums.nim and use nim to compile and execute it.

$ nim compile --run enums.nim
connected
idle

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