Go course

EnumsA String Method for Enums

Go

Display

Theme

Enums · Test exercise

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 default branch for unknown values, such as the result of the conversion Musim(9).
  • Inside String(), don't print m with %v or %s. That calls String() again and causes infinite recursion. Convert it to int(m) first, as in the example above.

For very long enums, the Go community often uses the stringer tool (go generate), which generates the String() 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:

  1. func (a Arah) String() string returns "Utara", "Timur", "Selatan", or "Barat". For any other value, return "Arah(N)"; for example, Arah(7) → "Arah(7)".
  2. func (a Arah) PutarKanan() Arah turns 90° clockwise (Barat → Utara).
  3. func (a Arah) PutarKiri() Arah turns 90° counterclockwise (Utara → Barat).
main.go
package main

import "fmt"

type Arah int

const (
	Utara Arah = iota
	Timur
	Selatan
	Barat
)

func (a Arah) String() string {
	// TODO: gunakan switch dan cabang default "Arah(N)"
	return ""
}

func (a Arah) PutarKanan() Arah {
	// TODO
	return a
}

func (a Arah) PutarKiri() Arah {
	// TODO
	return a
}

func main() {
	hadap := Utara
	fmt.Println("Ksatria menghadap", hadap)
	hadap = hadap.PutarKanan()
	fmt.Println("Belok kanan, sekarang menghadap", hadap)
	hadap = hadap.PutarKiri().PutarKiri()
	fmt.Println("Belok kiri dua kali, sekarang menghadap", hadap)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)