go reflect的使用

目录

New

通过reflect.Type创建对应的对象,比如:

func new(typ reflect.Type) (v reflect.Value) {
	if typ.Kind() == reflect.Ptr {
		v = reflect.New(typ.Elem())
	} else {
		v = reflect.New(typ).Elem()
	}
	return
}

elem()的作用就像是* ,如果typ的类型是指针,那么在New时,必须通过* 找到指针对应的结构体类型,否则New出来的只是一个指针。

而如果typ的类型不是指针,比如是结构体类型,那么在New时可以直接传入,最终New出来的是个地址,再次通过* 将地址转为结构体。

例如:

type Cat struct {
	name string
}

func main() {
	c := &Cat{}
	cv := new(reflect.TypeOf(c))
	fmt.Println(cv) // &{}

	c2 := Cat{}
	c2v := new(reflect.TypeOf(c2))
	fmt.Println(c2v) // {}
}

传入&cat{},返回&{};传入cat{},返回{}

posted @ 2022-09-12 23:32  moon_orange  阅读(26)  评论(0编辑  收藏  举报