My goal is to take a nil pointer to a struct (but could be any type), passed as an interface{}, and initialize a struct in its place.
My test code (playground link) is:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
Foo string
}
func main() {
var x *Foo
var y interface{} = x
fmt.Printf("Before: %#v\n", y)
fmt.Printf("Goal: %#v\n", interface{}(&Foo{}))
rv := reflect.ValueOf(y)
rv.Set(reflect.New(rv.Type().Elem()))
fmt.Printf("After: %#v\n", y)
}
I hope the code is self-documenting. But the goal is essentially to convert y which begins as an uninitialized pointer to Foo, ((*main.Foo)(nil)) into a pointer to an initialized (zero-value) instance ofFoo: &main.Foo{Foo:""}. But I'm getting reflect.Value.Set using unaddressable value. I don't understand why the value I'm attempting to set is unaddressable. I've spent the day reading through the source code to the standard library JSON unmarshaler, and other SO posts, but am still clearly overlooking something.
If I peel away the outer interface{}:
rv := reflect.ValueOf(y).Elem() // Remove the outer interface{}
rv.Set(reflect.New(rv.Type().Elem()))
the error becomes reflect: call of reflect.Value.Type on zero Value.
SomeUnmarshalWrapper(&result)followed byfunc SomeUnmarshalWrapper(i interface{}) { json.Unmarshal(&i) ...or similar.