|
|
|
|
|
by randomdata
783 days ago
|
|
> Enums and sum types seem to be related. They can certainly help solve some of the same problems. Does that make them related? I don't know. By definition, an enumeration is something that counts one-by-one. In other words, as is used in programming languages, a construct that numbers a set of named constants. Indeed you can solve the problem using that: type Temperature int
const (
Hot Temperature = iota
Cold
)
func SetThermostat(temperature Temperature) {
switch temperature {
case Hot:
fmt.Println("Hot")
case Cold:
fmt.Println("Cold")
}
}
But, while a handy convenience (especially if the set is large!), you don't even need enums. You can number the constants by hand to the exact same effect: type Temperature int
const (
Hot Temperature = 0
Cold Temperature = 1
)
func SetThermostat(temperature Temperature) {
switch temperature {
case Hot:
fmt.Println("Hot")
case Cold:
fmt.Println("Cold")
}
}
I'm not sure that exhibits any sum type properties. I guess you could see the value as being a tag, but there is no union. |
|
Refactoring is harder - when you add a new value to the enum, you can't easily find all those places that may require logic changes to handle the new value.
Enums are a big thing I miss when writing Go, compared to when writing C.