How does one achieve type-safe enums over a limited range of values in Go?
For example, suppose I wanted to model t-shirts with a simple Size and Color, both with limited possible values, ensuring that I could not create an instance with unsupported values.
I could declare the type Size
and Color
based on string
, define enums for the valid values, and a TShirt
type that uses them:
type Size string
const (
Small Size = "sm"
Medium = "md"
Large = "lg"
// ...
)
type Color string
const (
Red Color = "r"
Green = "g"
Blue = "b"
// ...
)
type TShirt struct {
Size Size
Color Color
}
var mediumBlueShirt = TShirt{Medium, Blue}
But how could I ensure that no TShirt with undefined size/color is created?
var doNotWant = TShirt{"OutrageouslyLarge", "ImpossibleColor"}