Open ns-cweber opened 6 years ago
This is a good idea and probably something I will want to add to the language. I want spend some time thinking about the best way to implement it, and I'm happy to discuss ideas here.
Relatedly, one of the big things I've been wanting to add to Go is proper enum support. Go can sort of emulate enums with the iota
keyword but it isn't strict enough compared to enums in other languages.
Consider this playground example:
package main
type Color uint
const (
Red Color = iota // 0
Green // 1
Blue // 2
)
func Paint(c Color) {
// Pretend we're doing something with the color here.
}
func main() {
// This works fine.
Paint(Blue)
// 3 does not correspond to a valid color, but the compiler doesn't stop you.
Paint(3)
}
I would like Fo to enable you to declare a Color
type with a limited set of valid values since that is usually what you want when talking about enums. If you try to use something other then Red
, Green
, or Blue
, it would be a compiler error.
Enums and sum types are closely related. For example, see this article explaining how enums/sum types work in Swift. Ideally I would like to come up with a single feature that solves several different use cases, including the one above.
fo should have proper sum types (as opposed to the interface{} workarounds in Go).
There are a couple of implementation options:
One is to build on interfaces. This is likely to incur a lot of unnecessary allocations. Another is to simulate C-style tagged unions (or Rust enums), but here you have to take care to not break garbage collection tracing.