```go
package main
import (
"fmt"
"reflect"
)
func main() {
t := test{a: 1, B: "123", c: 1.1, t: test1{a: 1, B: "123", c: 1.1}}
rangeStruct(t, func(k, v string) {
fmt.Printf("range:%s,%s\n", k, v)
})
t1 := &test{a: 2, B: "234", c: 2.2, t: test1{a: 2, B: "234", c: 2.2}}
rangeStruct(t1, func(k, v string) {
fmt.Printf("range:%s,%s\n", k, v)
})
}
type test struct {
a int
B string `json:"b"`
c float64
t test1
}
type test1 struct {
a int
B string `json:"b"`
c float64
}
func rangeStruct(in interface{}, h func(k, v string)) {
rType, rVal := reflect.TypeOf(in), reflect.ValueOf(in)
if rType.Kind() == reflect.Ptr { // 传入的in是指针,需要.Elem()取得指针指向的value
rType, rVal = rType.Elem(), rVal.Elem()
}
if rType.Kind() != reflect.Struct {
return
}
for i := 0; i < rType.NumField(); i++ { // 遍历结构体
t, f := rType.Field(i), rVal.Field(i)
// fmt.Printf("%v,%v\n", t, f)
// 此处可以参照f.String(),f.Int(),f.Float()源码,处理不同类型,我这里统一转成string类型了
if f.Kind() != reflect.Struct { // 不深入遍历结构体了,有需要自己实现吧
h(t.Name, fmt.Sprint(f))
}
}
}
```
#1
更多评论