gofsm

How to get all constants of a type in Go


Here is an example:

package main

type State int

const (
    Created State = iota
    Modified
    Deleted
)

func main() {
    // Some code here where I need the list
    // of all available constants of this type.
}

The use case for this is to create a Finite State Machine (FSM). Being able to get all constants will help me in writing a test case that will ensure that every new value has a corresponding entry in the FSM map.


Solution

  • If your constants are all in an order, you can use this:

    type T int
    
    const (
        TA T = iota
        TB
        TC
        NumT
    )
    
    func AllTs() []T {
        ts := make([]T, NumT)
        for i := 0; i < int(NumT); i++ {
            ts[i] = T(i)
        }
        return ts
    }
    

    You can also cache the output in e.g. init(). This will only work when all constants are initialised with iota in order. If you need something that works for all cases, use an explicit slice.