3 ms·
Not that it's a great solution, but there's https://github.com/BurntSushi/go-sumtype https://github.com/BurntSushi/go-sumtype for (2).
by cube2222 4y ago
Not that it's a great solution, but there's https://github.com/BurntSushi/go-sumtype https://github.com/BurntSushi/go-sumtype for (2).
- majewsky 4y agoThese sumtypes don't mesh well with JSON/YAML/etc. serialization though. If you have type MySumType interface { sealed() } like in the code example for go-sumtype, serialization is easy enough: type MySumType interface { json.Marshaler sealed() } But deserialization runs into a roadblock, because you cannot implement interfaces like json.Unmarshaler on an interface type. Something like type MySumType interface { json.Marshaler json.Unmarshaler sealed() } will not work: Given `var s MySumType`, json.Unmarshal() will croak because it cannot call UnmarshalJSON without knowing the concrete type of `s`. So for deserialization, you'd need an extra wrapper type that provides the json.Unmarshaler implementation.
- catlifeonmars 4y ago> But deserialization runs into a roadblock, because you cannot implement interfaces like json.Unmarshaler on an interface type. In addition to introducing the wrapper type, this could also be fixed by using a JSON decoder implementation that supports type/location hooks. In other words, this is more of a limitation of the custom unmarshaling mechanism chosen by the builtin encoding/json package.
- masklinn 4y ago> So for deserialization, you'd need an extra wrapper type that provides the json.Unmarshaler implementation. You'll probably need something along those lines either way, for the simple reason that there is no single mapping between sum types and JSON (or equivalent / similar) For instance serde provides 3 different serialisation schemes, and once in a while you still need a bespoke deserialiser.