反射
静态类型
静态类型就是变量声明赋予的类型,比如:
type MyInt int
type A struct{
Name string
}
var i *int
动态类型
动态类型:运行时给这个变量赋值时,这个值的类型(如果为nil的时候没有动态类型)。运行时,动态类型可能改变。例:
var A interface{}
A = 10 //动态int
A = "String" //动态String
var M *int
A = M //A的值可以改变
reflect对象
type Student struct {
Name string
Age int
School string
}
func (s Student) Say(msg string) {
fmt.Println("hello,", msg)
}
func (s Student) Say2(msg string) string {
return "say:" + msg
}
func (s Student) PrintInfo() {
fmt.Println(s)
}
func main() {
s1 := Student{"WZ", 19, "高中"}
fmt.Printf("%T\n", s1)
p1 := &s1
fmt.Printf("%T\n", p1)
fmt.Println(s1.Name)
fmt.Println((*p1).Name, p1.Name)
//value := reflect.ValueOf(&s1)
value := reflect.ValueOf(s1)
if value.Kind() == reflect.Ptr {
newValue := value.Elem()
fmt.Println(newValue.CanSet())
f1 := newValue.FieldByName("Name")
f1.SetString("zzy")
fmt.Println(s1)
}
//
methodValue1 := value.MethodByName("PrintInfo")
fmt.Printf("kind:%s,type:%s\n", methodValue1.Kind(), methodValue1.Type())
methodValue1.Call(nil)
arg1 := make([]reflect.Value, 0)
methodValue1.Call(arg1)
methodValue2 := value.MethodByName("Say")
arg2 := make([]reflect.Value, 1)
arg2[0] = reflect.ValueOf("msg")
methodValue2.Call(arg2)
methodValue3 := value.MethodByName("Say2")
arg3 := make([]reflect.Value, 1)
arg3[0] = reflect.ValueOf("msg")
callVal := methodValue3.Call(arg3)
fmt.Printf("%T\n", callVal)
str := callVal[0].Interface().(string)
fmt.Println(str)
}
标签:03,进阶,fmt,value,reflect,Println,Go,s1,string
From: https://www.cnblogs.com/huacha/p/16945022.html