Go does not support type-safe enums with structs in the same way as languages like C++ or Rust, but you can achieve type safety by defining a custom type and using constants with that type. Define a new type, assign constants to it, and use a switch statement or a map to enforce valid values at compile time.
type Status int
const (
StatusPending Status = iota
StatusActive
StatusClosed
)
func (s Status) String() string {
switch s {
case StatusPending:
return "Pending"
case StatusActive:
return "Active"
case StatusClosed:
return "Closed"
default:
return "Unknown"
}
}