Re:We Switched from Python to Go
by jrockway on Thursday October 27, 2022 @01:13AM
(#33353389)
`type` declares a type alias. `struct` defines a struct. If you're going to use your struct more than once, give it a name. If not, feel free not to.
The library "encoding/json" reads struct tags to figure out how to map names in JSON objects to the fields in the struct. It can guess, but you can also tell it. The convention `library:"expression"` is enforced by static analysis and is used throughout the standard library and ecosystem. It's not just for JSON.
Decode doesn't return the decoded value because it can't know the desired message type to return. "encoding/json" predates generics, but even with generics, it's not quite as simple as you think. With a decoding function like `func Decode[T any](data []byte) (T, error)`, you still have to invoke it as Decode[MessageType](data) in many circumstances.
Have a play with: https://go.dev/play/p/uKdS47KrsyR. You don't have to pass the result as an argument to decode, and there are no struct tags.
Finally, if you don't want a typed message, decode into a map[string]any. {"foo":{"bar"{"baz":123}}} decodes into an object that you can use like message["foo"]["bar"]["baz"]. Just hope that the server returned data according to the spec; it's shocking how often they don't.
The library "encoding/json" reads struct tags to figure out how to map names in JSON objects to the fields in the struct. It can guess, but you can also tell it. The convention `library:"expression"` is enforced by static analysis and is used throughout the standard library and ecosystem. It's not just for JSON.
Decode doesn't return the decoded value because it can't know the desired message type to return. "encoding/json" predates generics, but even with generics, it's not quite as simple as you think. With a decoding function like `func Decode[T any](data []byte) (T, error)`, you still have to invoke it as Decode[MessageType](data) in many circumstances.
Have a play with: https://go.dev/play/p/uKdS47KrsyR. You don't have to pass the result as an argument to decode, and there are no struct tags.
Finally, if you don't want a typed message, decode into a map[string]any. {"foo":{"bar"{"baz":123}}} decodes into an object that you can use like message["foo"]["bar"]["baz"]. Just hope that the server returned data according to the spec; it's shocking how often they don't.