Go course

InterfacesGetting to Know Interfaces

Go

Display

Theme

Interfaces · Test exercise

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:

  1. func (t Tunai) Biaya(belanja int) int — cash payments are free, so return 0.
  2. func (k KartuKredit) Biaya(belanja int) int — a credit card admin fee of belanja * k.Persen / 100 (integer division).
  3. func (e EWallet) Biaya(belanja int) int — a flat fee of e.BiayaTetap.
  4. func totalBayar(p Pembayaran, belanja int) int — return belanja plus the fee from payment method p.

Example: totalBayar(KartuKredit{Persen: 3}, 200000) returns 206000.

main.go
package main

import "fmt"

type Pembayaran interface {
	Biaya(belanja int) int
}

type Tunai struct{}

type KartuKredit struct {
	Persen int
}

type EWallet struct {
	BiayaTetap int
}

func (t Tunai) Biaya(belanja int) int {
	// TODO: pembayaran tunai gratis
	return -1
}

func (k KartuKredit) Biaya(belanja int) int {
	// TODO: belanja * persen / 100
	return 0
}

func (e EWallet) Biaya(belanja int) int {
	// TODO: biaya tetap
	return 0
}

func totalBayar(p Pembayaran, belanja int) int {
	// TODO: belanja + biaya dari p
	return 0
}

func main() {
	fmt.Println("Tunai:", totalBayar(Tunai{}, 150000))
	fmt.Println("Kartu kredit:", totalBayar(KartuKredit{Persen: 3}, 200000))
	fmt.Println("E-wallet:", totalBayar(EWallet{BiayaTetap: 1500}, 50000))
}

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)