Satisfying Several Interfaces
A single type can satisfy many interfaces at once — it just needs every method each interface asks for.
type Pembaca interface {
Baca() string
}
type Penulis interface {
Tulis(teks string)
}
type Buku struct {
isi string
}
func (b Buku) Baca() string { return b.isi }
func (b Buku) Tulis(teks string) { /* ... */ }
Buku is a Pembaca (reader) and a Penulis (writer).
Combining interfaces (embedding)
You can build an interface out of other interfaces by writing them inside it (embedding):
type PembacaPenulis interface {
Pembaca
Penulis
}
PembacaPenulis means "has a Baca and a Tulis method". Go's standard library uses this pattern, for example io.ReadWriter, which combines io.Reader and io.Writer.
Keep interfaces small
In Go, good interfaces are usually small — often just one or two methods. Small interfaces are easy for many types to satisfy and easy to combine when you need to. As the Go proverb goes: "The bigger the interface, the weaker the abstraction."
Functions should also ask for the smallest interface they need. A function that only reads should ask for a Pembaca, not a PembacaPenulis.
Task
An RPG has two abilities, each with its own small interface (already provided):
type Penyerang interface {
Serang() int
}
type Penyembuh interface {
Sembuhkan() int
}
type PenyerangPenyembuh interface {
Penyerang
Penyembuh
}
Penyerang is an attacker (Serang = attack), Penyembuh is a healer (Sembuhkan = heal), and PenyerangPenyembuh is both. Complete the code:
func (k Ksatria) Serang() int— returnk.Kekuatan * 2.func (p Paladin) Serang() int— returnp.Kekuatan + 5.func (p Paladin) Sembuhkan() int— returnp.Iman * 3.func totalDamage(a, b Penyerang) int— the sum ofSerang()from both attackers.func nilaiDukungan(x PenyerangPenyembuh) int— the sum ofSerang()andSembuhkan()fromx.
Example: nilaiDukungan(Paladin{Kekuatan: 10, Iman: 4}) returns 15 + 12 = 27.