Beginner question about pointer inconsistency

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!

Yes, but not related to unmarshalling. In main you do

json.Unmarshal(&dl, ...)
fmt.Printf(..., dl)

That is, you give the address (a pointer) to Unmarshal but print the struct value.

In the function example you give the pointer to your unmarshal function, then both Unmarshal into and print that pointer.


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:

Any ideas?


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. :slight_smile:

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.


This is great, @calmh, and makes total sense. Thanks so much for helping out a newbie!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.