Go course

InterfacesThe Stringer Interface

Go

Display

Theme

Interfaces · Output exercise

The Stringer Interface

One of the most widely used interfaces in Go's standard library lives in the fmt package:

type Stringer interface {
	String() string
}

Just one method! When you print a value with fmt.Println, fmt.Printf("%v"), or %s, the fmt package checks whether that value satisfies fmt.Stringer. If it does, it prints the result of String().

type Suhu struct {
	Celsius float64
}

func (s Suhu) String() string {
	return fmt.Sprintf("%.1f°C", s.Celsius)
}

fmt.Println(Suhu{Celsius: 28.5}) // 28.5°C

Without the String method, fmt.Println would print the raw struct contents, like {28.5}.

This is a great example of why small interfaces are powerful: the fmt package knows nothing at all about the Suhu (temperature) type, yet it can still display it nicely.

Careful: don't call fmt.Sprint(s) or use %v with s itself inside s's own String() method — that would call String() again, forever.

Task

In an RPG, characters get printed to the battle log. Right now the output is still the raw struct.

Add a method func (k Karakter) String() string so each character prints in this format:

<Nama> [<Kelas>] Lv.<Level> HP <HP>

That's the name, class, level, and HP. Don't change the main function. Expected output:

Aria [Penyihir] Lv.12 HP 340
Bima [Ksatria] Lv.15 HP 820
Citra [Pemanah] Lv.9 HP 275
Pemenang: Bima [Ksatria] Lv.15 HP 820
main.go
package main

import "fmt"

type Karakter struct {
	Nama  string
	Kelas string
	Level int
	HP    int
}

// TODO: tambahkan method String() string untuk Karakter

func main() {
	aria := Karakter{Nama: "Aria", Kelas: "Penyihir", Level: 12, HP: 340}
	bima := Karakter{Nama: "Bima", Kelas: "Ksatria", Level: 15, HP: 820}
	citra := Karakter{Nama: "Citra", Kelas: "Pemanah", Level: 9, HP: 275}

	fmt.Println(aria)
	fmt.Println(bima)
	fmt.Println(citra)
	fmt.Printf("Pemenang: %v\n", bima)
}

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)