Enums in Julia

Our enum type ServerState has an underlying Int type in Julia. Enumerated types (enums) are special in that they provide a way to define a type with a limited set of possible values, each with a distinct name.

struct ServerState
    value::Int
end

const StateIdle = ServerState(0)
const StateConnected = ServerState(1)
const StateError = ServerState(2)
const StateRetrying = ServerState(3)

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

state_name = Dict(
    StateIdle => "idle",
    StateConnected => "connected",
    StateError => "error",
    StateRetrying => "retrying"
)

function Base.show(io::IO, ss::ServerState)
    print(io, state_name[ss])
end

If we have a value of type Int, we cannot pass it to transition - the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums in Julia.

function main()
    ns = transition(StateIdle)
    println(ns)
    ns2 = transition(ns)
    println(ns2)
end

The transition function simulates a state transition for a server; it takes the existing state and returns a new state.

function transition(s::ServerState)::ServerState
    if s == StateIdle
        return StateConnected
    elseif s == StateConnected || s == StateRetrying
        return StateIdle
    elseif s == StateError
        return StateError
    else
        error("unknown state: $s")
    end
end

To run the program, put the code in a file and use Julia to execute it.

$ julia filename.jl
connected
idle

Now that we can run and build basic Julia programs, let’s learn more about the language.