这是一个例子:
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.
}
Run Code Online (Sandbox Code Playgroud)
用例是创建有限状态机(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
}
Run Code Online (Sandbox Code Playgroud)
您也可以在例如缓存输出init().这仅在所有常量iota按顺序初始化时有效.如果您需要适用于所有情况的内容,请使用显式切片.
在运行时无法执行此操作,因为无法使用反射包.您可以定义一个列表:
const(
Created State = iota
Modified
Deleted
)
var allStates = []State{Created, Modified, Deleted}
Run Code Online (Sandbox Code Playgroud)
您可以进一步添加字符串表示或任何其他数量的东西.
您可以从源代码生成这样的列表以使维护更容易,但我通常认为没有足够的时间来节省它.像stringer这样的工具已经能够做到这一点.
| 归档时间: |
|
| 查看次数: |
1063 次 |
| 最近记录: |