Reputation: 3941
I have the following Go code:
var typeRegistry = make(map[string]reflect.Type)
func init() {
typeRegistry["User"] = reflect.TypeOf(User{})
}
func makeInstance(name string) interface{} {
v := reflect.New(typeRegistry[name]).Elem()
return v.Interface()
}
func Invoke(any interface{}, name string, body []byte, signature Signature) {
args := signature.Args
data := makeInstance(signature.Args[0])
json.Unmarshal(body, &data)
inputs := make([]reflect.Value, len(args))
for i, _ := range signature.Args {
log.Println(reflect.TypeOf(data))
log.Println(reflect.ValueOf(data))
inputs[i] = reflect.ValueOf(data)
}
reflect.ValueOf(any).MethodByName(name).Call(inputs)
}
I'm attempting to pass in some JSON, and a string denoting what type the JSON should be mapped to. I'm attempting to use reflection to mush the two together again and pass it into a method by the methods name.
I kind of got it working, however, when I use a pointer un json.Unmarshal
it seems to lose the reference to its assigned type again, and defaults back to map[string]interface{}
which is a mis-match for the method I'm calling. In this case it's expecting type main.User
. If I remove the pointer from json.Unmarshal(body, data)
the types match correctly, but obviously the data is no longer being set for data
.
I'm aware I'm bastardising Go's type-system, and probably using the language in ways that isn't suggested, but I'm trying to do something more academic than useful, I guess.
Upvotes: 2
Views: 94
Reputation: 417702
You have to pass a pointer to json.Unmarshal()
, else it can't change the (pointed) data, only a copy of it. This is what happens when you pass data
: since it can't change the value (non-pointer value of type User
wrapped in interface{}
), therefore it creates a new value it can unmarshal into. And it will choose whatever it sees fit bests (but it won't be User
but rather map[string]interface{}
as you experienced).
So yes, you have to pass a pointer to it, but &data
will not be what you want. &data
will be a pointer to interface, of type *interface{}
because makeInstance()
returns a value of interface{}
type, so data
will have that inferred type.
The solution is to change makeInstance()
to return a pointer which may be wrapped in an interface{}
value, that's ok. And then you may simply pass data
to json.Unmarshal()
, because the data
interface value will hold a value of type *User
.
So do:
func makeInstance(name string) interface{} {
v := reflect.New(typeRegistry[name]) // Don't call Elem() here
return v.Interface()
}
And in Invoke()
:
data := makeInstance(signature.Args[0])
json.Unmarshal(body, data)
See related question that was posted just a few hours ago:
Store information/reference about structure
You can see a working demo here: Go Playground.
Upvotes: 3