by arhyth · 7y ago · 0 comments
(1) var thing Thing json.Unmarshall(reader, &thing)
(2) var thing *Thing = new(Thing) json.Unmarshall(reader, thing)
in (1) thing is a variable for a value of type Thing, while in (2) thing is a variable for a Thing pointer
shouldn't thing (2) need to be dereferenced first?
In C++ it would look like this:
(1) x = thing.Property;
(2) x = thing->Property; (or (*thing).Property)
but in go, both would look the same, like this: (1) x = thing.Property
(2) x = thing.Property
So there is a difference syntactically, and the compiler will handle them differently, but whether the difference is semantically relevant is debatable.They're semantically the same. The type of thing isn't, but that's syntax.
> Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.[1]
In (1) the '&' in '&thing' means roughly "the address of", so you are passing "the address of thing" i.e. a Thing pointer that points to the thing variable.