pointers - reflect.New returns <nil> instead of initialized struct -
i using reflection library i'm building there's don't understand reflect.new.
type struct { int b string } func main() { real := new(a) reflected := reflect.new(reflect.typeof(real)).elem().interface() fmt.println(real) fmt.println(reflected) } gives:
$ go run *go &{0 } <nil> isn't reflect.new supposed return &{0 } too? (runnable version)
ultimately, wish able iterate on fields of reflected struct (reflected.numfield() gives reflected.numfield undefined (type interface {} interface no methods)) , use setint, setstring , on.
thanks,
you used builtin new() function when created real variable, returns pointer! type of real *a, not a! source of confusion.
reflect.new() returns pointer (zeroed) value of given type (wrapped in reflect.value). if pass type a, wrapped *a, a initialized / zeroed. if pass type *a, wrapped **a, *a initialized (zeroed), , 0 value pointer type nil.
you ask reflect.new() create new value of pointer type (*a), , –as mentioned– 0 value nil.
you have pass type a (and not type *a). works (try on go playground):
real := new(a) reflected := reflect.new(reflect.typeof(real).elem()).elem().interface() fmt.println(real) fmt.println(reflected) or (go playground):
real := a{} reflected := reflect.new(reflect.typeof(real)).elem().interface() fmt.println(real) fmt.println(reflected)
Comments
Post a Comment