golang的反射

78 阅读1分钟
type TextMsg struct {
	Text string `json:"text"`
}

func TestReflect(t *testing.T) {
	m := &TextMsg{}
	fmt.Println(reflect.TypeOf(m))
	vptr := reflect.New(reflect.TypeOf(m))
	fmt.Println(vptr.Type())
	v := vptr.Elem()
	h := v.Type()
	for i := 0; i < h.NumField(); i++ {
		fmt.Println(h.Field(i))
	}
}

运行结果:=== RUN   TestReflect
*im.TextMsg
**im.TextMsg
--- FAIL: TestReflect (0.00s)
panic: reflect: NumField of non-struct type *im.TextMsg [recovered]
	panic: reflect: NumField of non-struct type *im.TextMsg

结论:reflect.New()会返回一个指向参数类型的新对象的指针,如果传入的本身是一个指针,则返回的就是二级指针