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
Post a Comment