Earlier quoted context omitted.
This might be a very simple and ignorant thought, but I'd be fine if they completely worked the same as Rust's enum's. [if let] is such a powerful feature, along with match arms.
Sure, but "the same as Rust's enums" including a mention of pattern matching, is a really big expenditure on the novelty budget from the point of view of Go. What Rust does there is perfectly normal... for an ML. But before Rust you didn't really see an ML down there counting CPU cycles, so this wasn't even on the radar when Go was invented. I think to do that you'd probably give up a lot of the simplicity Go is aimi…
Following the addition of type sets for generics I think go actually has all the pieces for union types already and it’s a matter of putting them all together at the compiler level:
- allow type sets as types (currently they’re only valid for constraints), probably excluding those using “underlying types”
- implement match completeness for type switches over type sets
And there you go, you’ve got unions from which you can easily implement sums via type declarations:
type Foo int
type Bar struct {}
type FooOrBar interface { Foo | Bar }
func Thing(v FooOrBar) {
switch vv := v.(type) {
case Foo:
// you have a foo
case Bar:
// you have a bar
// a default case is required if the cases are not exhaustive, forbidden if they are
}
}
Is this perfect? Not even remotely, this suffers from the usual Go issues of zero values, unenforceable constructors, and nil interfaces.But these are issues of the language, they should be fixed in the language in a hypothetical Go 2, I don’t think there is a good reason to try and work around them here.
Also completeness requirements could probably be extended to all “trivial” switches (types or values, not generalised expressions) via a go.mod stricture, similar to the new loop semantics.