Reflection of Pointer and Non-Pointer Types in Go

2021年11月16日 44点热度 0人点赞 0条评论
内容目录

reflect.Type.Elem() can return the type of the element, for example, for pointer types, it returns the type without the pointer.
reflect.Value.Elem() is used to obtain a reference to the value that the pointer points to.

type name struct {
}

func (n name) Print(str string) {

}

func main() {
	var n interface{} = &name{}
	t := reflect.TypeOf(n)
	var na interface{}

	// Instantiate
	if t.Kind() == reflect.Ptr {
		// Dereference pointer type
		elem := t.Elem()
		obj := reflect.New(elem)
		na = obj.Elem().Interface()
	} else {
		obj := reflect.New(t)
		na = obj.Elem().Interface()
	}

	nn := na.(name)
	nn.Print("aaa")
}

痴者工良

高级程序员劝退师

文章评论