Go course

InterfacesType Assertions

Go

Display

Theme

Interfaces · Test exercise

Type Assertions

A variable of interface type holds a concrete value inside it. Sometimes you need to get that concrete value back out, for example to read a field that isn't part of the interface. You do that with a type assertion:

var b Bentuk = Persegi{Sisi: 4}

p := b.(Persegi)      // ambil nilai Persegi dari b
fmt.Println(p.Sisi)   // 4

Here b.(Persegi) pulls the Persegi value out of b. If your guess about the type is wrong, this form will panic and the program stops. That's why you should almost always use the comma ok form:

l, ok := b.(Lingkaran)
if !ok {
	fmt.Println("b bukan Lingkaran")
}

(That prints "b isn't a Lingkaran" — a circle.)

  • If b really does hold a Lingkaran, ok is true and l holds the value.
  • If not, ok is false and l holds the zero value of Lingkaran — no panic.

A type assertion can also ask whether a value satisfies another interface:

if s, ok := b.(fmt.Stringer); ok {
	fmt.Println(s.String())
}

Task

A chat app sends notifications through several channels. They all satisfy the Notifikasi interface:

type Notifikasi interface {
	Isi() string
}

The Email, SMS, and Push types are already provided, along with their Isi() methods. Complete these two functions using a comma ok type assertion:

  1. func alamatEmail(n Notifikasi) (string, bool) — if n is an Email, return its Alamat (address) field and true; otherwise return "" and false.
  2. func biayaKirim(n Notifikasi) int — if n is an SMS, the sending cost is 350 (rupiah per SMS); other channels are free (0).
main.go
package main

import "fmt"

type Notifikasi interface {
	Isi() string
}

type Email struct {
	Alamat string
	Subjek string
}

type SMS struct {
	Nomor string
	Pesan string
}

type Push struct {
	Perangkat string
	Judul     string
}

func (e Email) Isi() string { return "Email: " + e.Subjek }
func (s SMS) Isi() string   { return "SMS: " + s.Pesan }
func (p Push) Isi() string  { return "Push: " + p.Judul }

func alamatEmail(n Notifikasi) (string, bool) {
	// TODO: gunakan n.(Email) dengan comma ok
	return "", false
}

func biayaKirim(n Notifikasi) int {
	// TODO: SMS berbiaya 350, lainnya 0
	return 0
}

func main() {
	var n Notifikasi = Email{Alamat: "dina@contoh.id", Subjek: "Pesan baru"}
	alamat, ok := alamatEmail(n)
	fmt.Println(n.Isi(), "->", alamat, ok)
	fmt.Println("Biaya:", biayaKirim(SMS{Nomor: "0812", Pesan: "Halo"}))
}

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)