-
Notifications
You must be signed in to change notification settings - Fork 1
/
enumFn.go
51 lines (46 loc) · 1.12 KB
/
enumFn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package utools
import "reflect"
func StructKeyIsExist(p interface{}, k string) bool {
return reflect.ValueOf(p).FieldByName(k).IsValid()
}
func EnumIntIsExist(p interface{}, k int, desc bool) (string, bool) {
ref := reflect.ValueOf(p)
for i := 0; i < ref.NumField(); i++ {
if ref.Field(i).Int() == int64(k) {
if desc {
return reflect.TypeOf(p).Field(i).Tag.Get("desc"), true
}
return "", true
}
}
return "", false
}
func EnumIntGetDesc(p interface{}, k int) string {
ref := reflect.ValueOf(p)
for i := 0; i < ref.NumField(); i++ {
if ref.Field(i).Int() == int64(k) {
return reflect.TypeOf(p).Field(i).Tag.Get("desc")
}
}
return ""
}
func EnumIntGetDescDefault(p interface{}, k int, def string) string {
if r := EnumIntGetDesc(p, k); r != "" {
return r
}
return def
}
func GetEnumKeyByValue(enum interface{}, v interface{}, k string) (s string) {
rvf := reflect.ValueOf(enum)
rtf := reflect.TypeOf(enum)
for i := 0; i < rtf.NumField(); i++ {
if reflect.DeepEqual(v, rvf.Field(i).Interface()) {
s = rtf.Field(i).Tag.Get(k)
if s == "" {
s = rtf.Field(i).Name
}
break
}
}
return s
}