go - Using reflect, how do you initialize value of a struct pointer field? -


package main  import (     "fmt"     "reflect" )  type struct {     d *int }  func main() {     := &a{}     v := reflect.valueof(a)     e := v.elem()     f := e.field(0)     z := reflect.zero(f.type().elem())     f.set(z)     fmt.println(z) } 

panic: reflect.set: value of type int not assignable type *int

how set *d default value use reflect

you need have pointer value (*int), reflect documentation states func zero(typ type) value that:

the returned value neither addressable nor settable.

in case can instead use new:

z := reflect.new(f.type().elem()) 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -