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%vwithsitself insides's ownString()method — that would callString()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