1 回答

TA貢獻1779條經驗 獲得超6個贊
func ListFields(a interface{}) {
rt := reflect.TypeOf(a) // take type of a
if rt.Kind() == reflect.Ptr {
rt = rt.Elem() // use Elem to get the pointed-to-type
}
if rt.Kind() == reflect.Slice {
rt = rt.Elem() // use Elem to get type of slice's element
}
if rt.Kind() == reflect.Ptr { // handle input of type like []*StructType
rt = rt.Elem() // use Elem to get the pointed-to-type
}
if rt.Kind() != reflect.Struct {
return
}
fmt.Printf(" Kind: %+v \n", rt)
for _, f := range reflect.VisibleFields(rt) {
if f.IsExported() {
fmt.Printf(" Kind: %+v \n", f)
} else {
fmt.Printf(" Kind: %s \n", f.Name)
}
}
}
https://go.dev/play/p/0J3VXmFPe87
- 1 回答
- 0 關注
- 113 瀏覽
添加回答
舉報