3 ms·
Do you have any examples of how you would implement a makeshift sum type like your example?
by mssundaram 6y ago
Do you have any examples of how you would implement a makeshift sum type like your example?
- morelisp 6y agoX interface{} // int(3) | int(5) | []float64 | *Z It sucks.
- throwaway894345 6y agoWe can recoup a fair bit more type safety than this if we're interested in going through the effort: https://play.golang.org/p/4Fd7aKRtmvz https://play.golang.org/p/4Fd7aKRtmvz. See my sibling comment for more details.
- throwaway894345 6y agoHere's one such workaround: https://play.golang.org/p/4Fd7aKRtmvz https://play.golang.org/p/4Fd7aKRtmvz It's not great for a number of reasons. First of all, `nil` is always a valid permutation even if we don't want it to be. Secondly, it's a lot of work to express the constraints we want. Thirdly, it's not perfectly type-safe; someone who was determined to shoot themselves in the foot could construct other instances of our "singleton types" if they really wanted to. Fourthly, boxing all of these values will almost certainly cause unnecessary allocations which would be a bummer if we wanted to create a lot of these quickly (this is an implementation detail and may not be any worse than a language with first-class support for sum types).
- morelisp 6y agoFifth, and most critically for me why it’s not really any better than a comment on an interface{}: a user’s matches won’t be checked for exhaustiveness if you add a new type, let alone them poking around the internals. You can box them safely, but not unbox them.
- throwaway894345 6y agoYes, that’s an important point; thanks for noting.
- deleted 6y ago[deleted]