直接上代码:
package main import ( "fmt" "reflect" ) func main() { var n = 33 var pn = &n var ppn = &pn // new可以定义不同类型的地址,可以是int/int*/int**,都是可以的,对应的值也是需要正确的 { nNew := reflect.New(reflect.TypeOf(n)) nNew.Elem().Set(reflect.ValueOf(n)) //pnew.Elem().Set(reflect.ValueOf(pn))// reflect.Set: value of type *int is not assignable to type int //pnew.Elem().Set(reflect.ValueOf(ppn)) // reflect.Set: value of type **int is not assignable to type int fmt.Println(nNew) } { pnNew := reflect.New(reflect.TypeOf(pn)) //pnew.Elem().Set(reflect.ValueOf(n)) // reflect.Set: value of type int is not assignable to type *int pnNew.Elem().Set(reflect.ValueOf(pn)) { nNew := reflect.New(reflect.TypeOf(n)) nNew.Elem().Set(reflect.ValueOf(n)) pnNew.Elem().Set(nNew) } //pnew.Elem().Set(reflect.ValueOf(ppn)) // reflect.Set: value of type **int is not assignable to type *int fmt.Println(pnNew) } { types := reflect.TypeOf(ppn).String() fmt.Println(types) ppnNew := reflect.New(reflect.TypeOf(ppn)) //pnew.Elem().Set(reflect.ValueOf(n)) // reflect.Set: value of type int is not assignable to type **int // pnew.Elem().Set(reflect.ValueOf(pn)) // reflect.Set: value of type *int is not assignable to type **int ppnNew.Elem().Set(reflect.ValueOf(ppn)) { pnNew := reflect.New(reflect.TypeOf(pn)) { nNew := reflect.New(reflect.TypeOf(n)) nNew.Elem().Set(reflect.ValueOf(n)) pnNew.Elem().Set(nNew) } ppnNew.Elem().Set(pnNew) } fmt.Println(ppnNew) } }
reflect.New()后面的类型可以是int/int*/int**, 也就是可以是对象/指针/指针的指针
然后设置值的时候需要一一对应上
标签:reflect,Set,研究,ValueOf,Elem,golang,int,New,type From: https://www.cnblogs.com/zhanchenjin/p/16954442.html