-
Notifications
You must be signed in to change notification settings - Fork 3
/
gtbox_reflect.go
70 lines (65 loc) · 1.9 KB
/
gtbox_reflect.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Package gtbox_reflect 反射方法工具库
*/
package gtbox_reflect
import (
"fmt"
"reflect"
)
// GetNumberOfFieldWithModel 获取Model的字段数量支持指针、非指针传入
func GetNumberOfFieldWithModel(customModel interface{}) int {
typ := reflect.TypeOf(customModel)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() == reflect.Struct {
numFields := typ.NumField()
return numFields
} else {
return 0
}
}
// GetFieldNameAtIndex 获取指定索引位置的--字段名
func GetFieldNameAtIndex(customModel interface{}, index int) (string, error) {
typ := reflect.TypeOf(customModel)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() == reflect.Struct {
if index >= 0 && index < typ.NumField() {
return typ.Field(index).Name, nil
}
return "", fmt.Errorf("Index out of range")
}
return "", fmt.Errorf("Provided interface is not a struct or pointer to struct")
}
// GetFieldValueAtIndex 获取指定索引位置的字段--Value值
func GetFieldValueAtIndex(customModel interface{}, index int) (interface{}, error) {
val := reflect.ValueOf(customModel)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() == reflect.Struct {
if index >= 0 && index < val.NumField() {
return val.Field(index).Interface(), nil
}
return nil, fmt.Errorf("Index Out Of Range")
}
return nil, fmt.Errorf("Provided interface is not a struct or pointer to struct")
}
// GetFieldIndex 获取给定字段名在结构体中的索引
func GetFieldIndex(customModel interface{}, fieldName string) (int, error) {
typ := reflect.TypeOf(customModel)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() == reflect.Struct {
for i := 0; i < typ.NumField(); i++ {
if typ.Field(i).Name == fieldName {
return i, nil
}
}
return -1, fmt.Errorf("Field not found")
}
return -1, fmt.Errorf("Provided interface is not a struct or pointer to struct")
}