反射机制:反射是指一类应用,它们能够自描述和自控制。
type StA struct {
Name string
Age int
}
func (s StA) Info(str string) (a bool, b int) {
fmt.Println("Name =", s.Name, "Age =", s.Age, "Score =", str)
return true, 5
}
//-- 反射测试 (反射: 自描述和自控制)
func reflectTest() {
var str = "Im hero"
//-- 反射获取基本信息类型
fmt.Println("str's Tpye is", reflect.TypeOf(str))
//-- 反射获取值
fmt.Println("str's Value is", reflect.ValueOf(str))
//-- 反射获取结构体信息类型
var s StA
sb := &StA{
Name: "BBC",
Age: 18,
}
fmt.Println("s's Tpye is", reflect.TypeOf(s))
fmt.Println("sb's Tpye is", reflect.TypeOf(sb))
fmt.Println("s's Value is", reflect.ValueOf(s))
fmt.Println("sb's Value is", reflect.ValueOf(sb))
//-- 类型的比较
if reflect.TypeOf(str).Kind() == reflect.String {
fmt.Println("typexKind is string")
}
//-- Go 语言反射获取变量所指向的指针语法:
// reflect.ValueOf(varname).Elem()
//-- 空值判断
//-- 尝试从结构体中查找一个不存在的字段
//-- 尝试从结构体查找一个不存在的方法
//-- 通过反射可以修改 结构体字段的值
reflect.ValueOf(&sb.Age).Elem().SetInt(20)
fmt.Println("sb's Value is", reflect.ValueOf(sb))
fmt.Println("sb's is", (sb))
//-- 反射执行结构体方法
infoFunc := reflect.ValueOf(sb).MethodByName("Info")
args := []reflect.Value{reflect.ValueOf("bujihge")}
//res := infoFunc.Call([]reflect.Value{})
res := infoFunc.Call(args)
fmt.Println("Pass =", res[0].Bool())
}