Re:Value-Oriented Programming
by marcus_holmes on Saturday September 01, 2018 @01:40PM
(#17892972)
thanks :) I get this now. This would be useful if Go supported it.
I've used enums before (but just as constant values), and I'd love to have them in Go. Iota is nice, but as you say there's no constraint on the type. It seems like a good fit...
To do what he proposes, you need sum types akin to what Rust calls enums. In Rust it would be something like:
The idea is that you have a value declared as Path, you can only assign Arc and Line to it. Similarly, if you want use a value, you have to match against it: or you can destructure: Languages that have sum types are usually expression-based, so the compiler insists that your match is exhaustive, or it won't compile: The closest Go has, as I said in my comment, is the ability to unify multiple structs with a dummy interface, e.g.: Now you can do a type switch: However, since Go's interfaces are implicit, it doesn't know that Arc and Line fulfill a possible union of types, and so the switch cannot fail if it's not exhaustive: I'd love to have sum types in Go; it feels like a fairly natural fit for the language since we already have high-level constructs like interfaces: The syntax for matching could be exactly the same as today, even. It would be to cool to be able match with destructuring, but given that Go doesn't support any destructuring today, I'm OK with this being left out to keep the language small.As an aside, it's important to note that in Rust, enums aren't just structs; they can be tuples, too, or constant values:
Here, a value of type State can be either Alive or Dead: And you can pattern match against it. The closest Go has to this is numeric constants with help from the iota keyword: But yet again, this is a hack that doesn't provide much type-system safety: