3 ms·
just new to Golang (in programming in general, actually) and this bug me. in the slide, it's indicated they are semantically the same. but how? (1) var thing T
by arhyth 7y ago
just new to Golang (in programming in general, actually) and this bug me. in the slide, it's indicated they are semantically the same. but how?
(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?
- eraxley 7y agoYou are right that (2) needs to be dereferenced first, however, in go a pointer is autmatically dereferenced when accessing its properties or "methods". What I mean by this is that if you want to access a property on thing, it would look the same. 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.
- derangedHorse 7y agoThat's one of the things that I hate about Go. That and how they force me to write an 'else' on the same line as the closing brace of the 'if'.
- saagarjha 7y agoRust does this too, I think.
- steveklabnik 7y ago(Yes, it does.)
- falsedan 7y agojson.Unmarshall takes a pointer as its second parameter. In (1), a pointer to thing is created using &. In (2), thing is already a pointer and can be passed as-is. They're semantically the same. The type of thing isn't, but that's syntax.
- ttctciyf 7y agoWell, the second arg of Unmarshall is expected to be some kind of pointer. > 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. 1: https://golang.org/src/encoding/json/decode.go https://golang.org/src/encoding/json/decode.go