A String Method for Enums
int-based enums have a weakness: when you print one, all you get is a number.
fmt.Println(Hujan) // 1 — kurang informatif
The fix is to give the enum type a String() string method. The fmt package checks whether a value satisfies the fmt.Stringer interface:
type Stringer interface {
String() string
}
If it does, fmt.Println, %v, and %s use the result of String():
func (m Musim) String() string {
switch m {
case Kemarau:
return "Kemarau"
case Hujan:
return "Hujan"
default:
return fmt.Sprintf("Musim(%d)", int(m))
}
}
fmt.Println(Hujan) // Hujan
fmt.Printf("%v | %d\n", Hujan, Hujan) // Hujan | 1
Two things to notice:
- Always provide a
defaultbranch for unknown values, such as the result of the conversionMusim(9). - Inside
String(), don't printmwith%vor%s. That callsString()again and causes infinite recursion. Convert it toint(m)first, as in the example above.
For very long enums, the Go community often uses the
stringertool (go generate), which generates theString()method for you.
Other methods on enums
Since an enum is a named type, you're free to add other methods. For example, you can compute the next value, wrapping around, with modulo:
func (h Hari) Besok() Hari {
return (h + 1) % 7
}
Task
In an RPG, a character faces one of four directions, Arah: Utara, Timur, Selatan, Barat (north, east, south, west; already defined with iota, in clockwise order). Complete:
func (a Arah) String() stringreturns"Utara","Timur","Selatan", or"Barat". For any other value, return"Arah(N)"; for example,Arah(7)→"Arah(7)".func (a Arah) PutarKanan() Arahturns 90° clockwise (Barat→Utara).func (a Arah) PutarKiri() Arahturns 90° counterclockwise (Utara→Barat).