course/reflector/struct_reflector.go

47 lines
1.1 KiB
Go

package main
import (
"fmt"
"reflect"
)
type student struct {
Name string `json:"name"`
Score int `json:"score"`
}
var stu1 = student{
Name: "小王子",
Score: 90,
}
func main() {
t := reflect.TypeOf(stu1)
fmt.Println(t.Name(), t.Kind()) // student struct
fmt.Println(t.NumField()) //2
// 通过for循环遍历结构体的所有字段信息
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Println(field)
fmt.Printf("name:%s index:%d type:%v json tag:%v\n", field.Name, field.Index, field.Type, field.Tag.Get("json"))
}
// 通过字段名获取指定结构体字段信息
if scoreField, ok := t.FieldByName("Score"); ok {
fmt.Printf("name:%s index:%d type:%v json tag:%v\n", scoreField.Name, scoreField.Index, scoreField.Type, scoreField.Tag.Get("json"))
}
fmt.Println("======================ValueOf==================")
v := reflect.ValueOf(stu1)
fmt.Println(v.NumField()) //2
for i := 0; i < v.NumField(); i++ {
field2 := v.Field(i)
fmt.Println(field2)
} //遍历值
wangzi := v.FieldByName("Name")
fmt.Println(wangzi)
}