原址:https://blog.csdn.net/qq_40422846/article/details/87536312
package main
import (
"reflect"
"fmt"
)
type User struct {
Id int
Name string
Age int
}
func main() {
u := User{1,"xiaozhi",26}
info(u)
}
func info(i interface{}) {
t := reflect.TypeOf(i)
fmt.Println("Type: ", t.Name())
v := reflect.ValueOf(i)
fmt.Println("Fields: ")
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
val := v.Field(i).Interface()
fmt.Printf("%6s: %v = %v\n",f.Name,f.Type,val)
}
}
输出结果
Type: User
Fields:
Id: int = 1
Name: string = xiaozhi
Age: int = 26