Created
August 23, 2018 16:14
-
-
Save karlmutch/8cb3fc8704bf6e89029ee0247071b5ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Found at https://play.golang.org/p/pQn_doizkn_L | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
var strs = make(map[reflect.Type]map[int]string) | |
func Register(t reflect.Type, v int, s string) { | |
m, ok := strs[t] | |
if !ok { | |
m = make(map[int]string) | |
strs[t] = m | |
} | |
m[v] = s | |
} | |
func GetStr(e interface{}) string { | |
t := reflect.TypeOf(e) | |
v := int(reflect.ValueOf(e).Int()) | |
return strs[t][v] | |
} | |
func InitEnums(estr interface{}) { | |
v := reflect.ValueOf(estr).Elem() | |
vt := v.Type() | |
for i, n := 0, v.NumField(); i < n; i += 1 { | |
f := v.Field(i) | |
Register(f.Type(), i, string(vt.Field(i).Tag)) | |
f.SetInt(int64(i)) | |
} | |
} | |
type Enum int | |
func (e Enum) String() string { return GetStr(e) } | |
var Enums struct { | |
Alpha Enum "Alpha" | |
Beta Enum "Beta" | |
} | |
func main() { | |
InitEnums(&Enums) | |
fmt.Printf("%+v\n", Enums) | |
fmt.Printf("%v\n", Enums.Alpha.String()) | |
fmt.Printf("%v\n", Enums.Beta) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment