请教大佬, go 如何根据变量名获取该变量的数据
比如有
const ( A iota B C D ) a := []string{"A", "B", "D"}
如何获取 a 中每个元素的值。即得到 0 1 3
之前想用 map,可是如果 cont 里是 A–Z 的话就非常麻烦了,有什么好的办法么
比如有
const ( A iota B C D ) a := []string{"A", "B", "D"}
如何获取 a 中每个元素的值。即得到 0 1 3
之前想用 map,可是如果 cont 里是 A–Z 的话就非常麻烦了,有什么好的办法么
map 倒是可以实现。
安装 stringer
“`shell
go get -u -a golang.org/x/tools/cmd/stringer
“`
**permission.go**
“`golang
package core
import (
“sort”
“strings”
)
//go:generate stringer –type Permission
type Permission int
const (
A Permission = iota
B
C
D
E
F
)
func PermissionFromName(p string) (Permission, bool) {
idx := strings.Index(_Permission_name, p)
if idx < 0 {
return 0, false
}
pos := sort.Search(len(_Permission_index), func(i int) bool {
return _Permission_index[i] >= uint8(idx)
})
return Permission(pos), true
}
“`
执行 go generate
“`shell
go generate ./…
“`
生成 **permission_string.go** 文件
“`golang
// Code generated by “stringer –type Permission”; DO NOT EDIT.
package core
import “strconv”
func _() {
// An “invalid array index” compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[A-0]
_ = x[B-1]
_ = x[C-2]
_ = x[D-3]
_ = x[E-4]
_ = x[F-5]
}
const _Permission_name = “ABCDEF”
var _Permission_index = […]uint8{0, 1, 2, 3, 4, 5, 6}
func (i Permission) String() string {
if i < 0 || i >= Permission(len(_Permission_index)-1) {
return “Permission(” + strconv.FormatInt(int64(i), 10) + “)”
}
return _Permission_name[_Permission_index[i]:_Permission_index[i+1]]
}
“`
最后,可以使用 Permission.String() 方法将 enum 转成 string,也可以用 PermissionFromName() 转回来。enum 有变动的时候,重新执行一下 go generate 重新生成代码即可。
https://gist.github.com/yiplee/5c69cde11f80c9de1afe7402ad5f4b30