package main
import (
. "fmt"
"reflect"
)
/*标题: 反射*/
// 获得变量类型
func reflectType(x interface{}) {
v := reflect.TypeOf(x)
Println("type:", v, "\ttype name:", v.Name(), "\ttype kind:", v.Kind())
}
type cat struct {}
func reflectTypeTest() {
// 输出: type: float32 type name: float32 type kind: float32
reflectType(float32(3.14))
// 输出: type: int64 type name: int64 type kind: int64
reflectType(int64(100))
// 输出: type: main.cat type name: cat type kind: struct
reflectType(cat{})
}
// 通过反射设置值(传入的参数必须是指针)
func reflectSetValue(x interface{}) {
v := reflect.ValueOf(x)
if v.Elem().Kind() == reflect.Int64 {
// Elem 返回v包含的值, 或者v指向的数. v必须是接口或指针.
v.Elem().SetInt(200)
}
}
func reflectSetValueTest() {
var i int64 = 100
reflectSetValue(&i)
Println("i =", i)
}
// IsValid和IsNil测试
func ValidOrNil() {
var a *int
Println("var a *int IsNil:", reflect.ValueOf(a).IsNil())
Println("nil IsValid:", reflect.ValueOf(nil).IsValid())
b := struct {}{}
Println("不存在的结构体成员:", reflect.ValueOf(b).FieldByName("abc").IsValid())
Println("不存在的结构体方法:", reflect.ValueOf(b).MethodByName("abc").IsValid())
c := map[string]int{}
Println("Map中不存在的键:", reflect.ValueOf(c).MapIndex(reflect.ValueOf("张飞")).IsValid())
}
// 结构体反射
type student struct {
Name string `json:"name"` // 最后的部分称为tag
Score int `json:"score"`
}
func structReflectTest() {
s := student{
Name: "张飞",
Score: 40,
}
t := reflect.TypeOf(s)
Println(t.Name(), t.Kind()) // student struct
// 遍历结构体的成员变量
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
Printf("name:%s\tindex:%d\ttype:%v\tjson tag:%v\n", field.Name, field.Index, field.Type, field.Tag.Get("json"))
}
// 通过字段名获得结构体信息
if field, ok:=t.FieldByName("Name"); ok {
Printf("name:%s\tindex:%d\ttype:%v\tjson tag:%v\n", field.Name, field.Index, field.Type, field.Tag.Get("json"))
}
// 遍历结构体的所有方法
for i := 0; i < t.NumMethod(); i++ {
method := t.Method(i)
Printf("name:%s\tindex:%d\ttype:%v\tfunc:%v\n", method.Name, method.Index, method.Type, method.Func)
}
}
Go语言学习草稿(9) 反射
最新推荐文章于 2024-03-29 15:30:59 发布