Getting to Know Interfaces
An interface is a set of method signatures. An interface doesn't care how something works, only what it can do.
type Bentuk interface {
Luas() float64
Keliling() float64
}
Bentuk (shape) asks for an area (Luas) and a perimeter (Keliling). Any type that has all of those methods automatically satisfies the Bentuk interface. Go has no implements keyword — the implementation is implicit:
type Persegi struct {
Sisi float64
}
func (p Persegi) Luas() float64 { return p.Sisi * p.Sisi }
func (p Persegi) Keliling() float64 { return 4 * p.Sisi }
Since Persegi has both Luas and Keliling methods, a Persegi value can be used anywhere a Bentuk is needed:
func cetakInfo(b Bentuk) {
fmt.Println("Luas:", b.Luas(), "Keliling:", b.Keliling())
}
cetakInfo(Persegi{Sisi: 3})
The cetakInfo function doesn't know (and doesn't need to know) the concrete type it receives. That's the power of interfaces: the same code can work with many types.
If a type forgets to implement one of the methods, the compiler will reject it as soon as you try to use it as that interface.
Task
An online store supports several payment methods. Each method satisfies this interface (already in the editor):
type Pembayaran interface {
Biaya(belanja int) int
}
Biaya returns the fee for a purchase amount (belanja). Complete the code:
func (t Tunai) Biaya(belanja int) int— cash payments are free, so return0.func (k KartuKredit) Biaya(belanja int) int— a credit card admin fee ofbelanja * k.Persen / 100(integer division).func (e EWallet) Biaya(belanja int) int— a flat fee ofe.BiayaTetap.func totalBayar(p Pembayaran, belanja int) int— returnbelanjaplus the fee from payment methodp.
Example: totalBayar(KartuKredit{Persen: 3}, 200000) returns 206000.