这是一个例子:
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.
}
此用例是创建有限状态机 (FSM)。能够获取所有常量将帮助我编写测试用例,以确保每个新值在 FSM 映射中都有对应的条目。
最佳答案
如果你的常量都是有序的,你可以这样使用:
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
}
您还可以将输出缓存在例如初始化()
。这只有在所有常量都按顺序用 iota
初始化时才有效。如果您需要适用于所有情况的东西,请使用显式 slice 。
关于go - 如何在 Go 中获取一个类型的所有常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888678/