I seem to be getting inconsistent results using the json.Unmarshal function depending on whether it’s called from within main() or within a function. Here is my code:
When run, the first Printf statement within main prints a value of type main.Location, whereas the Printf statement within my main.unmarshal function prints a value of type *main.Location. Why is there a discrepancy? Does it have to do with the way interface{} arguments are passed?
Sorry if this is remedial… Any help would be appreciated. Thanks!
Thanks for the rapid response - that makes sense, but then I have a supplemental problem.
When, instead, I pass the struct value to my unmarshal function rather than a pointer, and pass the address of that struct value to json.Unmarshal (as required by the documentation for the json package), the Unmarshal function incorrectly identifies the struct as a map as per the following code:
Yeah, you can’t do that. What happens in your latest sample is that you pass a struct value in the interface (it gets copied). You can view the interface as a kind of box. You then pass a pointer to the interface (&x) to Unmarshal. It will Unmarshal into whatever is pointed-to, in this case an interface{}, and since that’s not a concrete type it defaults to a map.
Your first attempt was correct, imho.
With the exception that perhaps avoid interface{} altogether and pass a *Location when you don’t need the generality of the empty interface. That makes it altogether clearer what’s going on.