Switching on Enums
Enums and switch are a natural pair. A single switch can spell out the business rule for each enum value very clearly.
func (l Lampu) Berikutnya() Lampu {
switch l {
case Merah:
return Hijau
case Hijau:
return Kuning
case Kuning:
return Merah
default:
return l
}
}
Several values in one case
A case can list several values separated by commas:
func (h Hari) AkhirPekan() bool {
switch h {
case Sabtu, Minggu:
return true
default:
return false
}
}
Don't forget default
Go doesn't force a switch to cover every enum value. If one day you add a new constant (say, Dikembalikan, "returned"), old switch statements won't warn you. Good habits:
- Always write a
defaultbranch, and return an error or a safe value there for unexpected cases. - When you add a new enum value, look for every
switchthat uses that type.
Some linters (for example
exhaustive) can check that aswitchon an enum covers every constant.
State machines
Many business flows are a sequence of states with strict rules about how you move between them. An enum plus a switch writes those rules down explicitly in one place, and errors prevent invalid transitions.
Task
An online store tracks StatusPesanan (order status): Menunggu (pending), Dibayar (paid), Dikirim (shipped), Selesai (completed), Dibatalkan (canceled). Its String() method is already provided, and so are the errors ErrStatusAkhir and ErrStatusTidakValid. Complete two functions using switch:
func Lanjut(s StatusPesanan) (StatusPesanan, error)returns the next status in the normal flow:Menunggu→Dibayar→Dikirim→Selesai.SelesaiandDibatalkanare final states: return the same status andErrStatusAkhir.- Any other value: return the same status and
ErrStatusTidakValid.
func BisaDibatalkan(s StatusPesanan) boolreturnstrueonly forMenungguandDibayar(an order that has already shipped can't be canceled). Use a singlecasewith two values.