Validating Enum Values
An enum in Go is just a named type on top of int, so the compiler does not stop you from using values that were never defined:
var s Status = 42 // sah secara sintaks, padahal tidak ada Status 42
Stray values like this often come from outside the program: user input, config files, databases, or API requests. That's why an important enum should have a way to validate itself.
Make the zero value "unknown"
An enum variable you forget to set will be 0. If 0 is a valid choice (say, Admin), a bug can quietly hand out too much access! The safe pattern is to reserve 0 for an unknown value:
type Level int
const (
LevelTidakDikenal Level = iota // 0 — zero value, tidak valid
LevelPemula
LevelMahir
)
A Valid method
With consecutive constants, validation is just a range check:
func (l Level) Valid() bool {
return l >= LevelPemula && l <= LevelMahir
}
Parsing from a string
Data from outside usually arrives as text. A parse function turns the text into an enum and returns an error if the text isn't recognized, following the error patterns from earlier chapters:
var ErrLevelTidakValid = errors.New("level tidak valid")
func ParseLevel(s string) (Level, error) {
switch s {
case "pemula":
return LevelPemula, nil
case "mahir":
return LevelMahir, nil
}
return LevelTidakDikenal, fmt.Errorf("%w: %q", ErrLevelTidakValid, s)
}
Wrapping with %w lets the caller check errors.Is(err, ErrLevelTidakValid) while still getting a clear message.
Task
A chat app has a Peran (role) enum for group members: PeranTidakDikenal (0, unknown), Tamu (guest), Anggota (member), Moderator, Admin. The ErrPeranTidakValid error is already provided. Complete:
func (p Peran) Valid() boolreturnstrueonly forTamuthroughAdmin.func ParsePeran(s string) (Peran, error)accepts"tamu","anggota","moderator","admin", ignoring case and leading/trailing spaces (hint:strings.ToLowerandstrings.TrimSpace). Any other text producesPeranTidakDikenaland an error that wrapsErrPeranTidakValidwith%w.