Go course

InterfacesType Switches and any

Go

Display

Theme

Interfaces · Test exercise

Type Switches and any

The empty interface: any

An interface with no methods at all — interface{} — is satisfied by every type, since every type has "at least zero methods". Since Go 1.18 there's a friendlier alias for it: any.

var x any
x = 42
x = "halo"
x = Buku{Judul: "Laskar Pelangi"}

any is useful when a value really could be of any type (like the parameters of fmt.Println). But don't overdo it: with any you lose the compiler's type checking. To use what's inside, you still have to find out its actual type.

Type switches

When there are many possible types, writing type assertions over and over gets tiring. Use a type switch instead:

func jelaskan(v any) string {
	switch x := v.(type) {
	case int:
		return fmt.Sprintf("bilangan bulat %d", x)
	case string:
		return "teks " + x
	case nil:
		return "tidak ada nilai"
	default:
		return fmt.Sprintf("tipe lain: %T", x)
	}
}

This describes the value as an integer, text, no value, or "some other type".

  • v.(type) can only be used inside a switch.
  • In each case, the variable x already has that case's type (in case int, x is an int).
  • case nil matches when the interface holds no value at all.
  • default handles any type that isn't listed.

Task

A library catalog system stores different kinds of items. The Buku (book), Majalah (magazine), and DVD types are already provided. Complete func labelKoleksi(k any) string with a type switch:

Value of kResult
BukuBuku: <Judul> oleh <Penulis>
MajalahMajalah: <Judul> edisi <Edisi>
DVDDVD: <Judul> (<Durasi> menit)
stringCatatan: <isi string>
nilKosong
any other typeTidak dikenal

(In English: Book: <Title> by <Author>, Magazine: <Title> issue <Issue>, DVD: <Title> (<Duration> minutes), Note: <the string>, Empty, and Unknown.)

Example: labelKoleksi(DVD{Judul: "Petualangan Sherina", Durasi: 112}) → DVD: Petualangan Sherina (112 menit).

Tip: fmt.Sprintf makes it easy to build strings that contain numbers.

main.go
package main

import "fmt"

type Buku struct {
	Judul   string
	Penulis string
}

type Majalah struct {
	Judul string
	Edisi int
}

type DVD struct {
	Judul  string
	Durasi int
}

func labelKoleksi(k any) string {
	// TODO: gunakan type switch
	return ""
}

func main() {
	fmt.Println(labelKoleksi(Buku{Judul: "Bumi Manusia", Penulis: "Pramoedya Ananta Toer"}))
	fmt.Println(labelKoleksi(Majalah{Judul: "Sains Kita", Edisi: 42}))
	fmt.Println(labelKoleksi(DVD{Judul: "Petualangan Sherina", Durasi: 112}))
	fmt.Println(labelKoleksi("rak 3 sedang diperbaiki"))
	fmt.Println(labelKoleksi(nil))
	fmt.Println(labelKoleksi(3.14))
}

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)