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 aswitch.- In each
case, the variablexalready has that case's type (incase int,xis anint). case nilmatches when the interface holds no value at all.defaulthandles 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 k | Result |
|---|---|
Buku | Buku: <Judul> oleh <Penulis> |
Majalah | Majalah: <Judul> edisi <Edisi> |
DVD | DVD: <Judul> (<Durasi> menit) |
string | Catatan: <isi string> |
nil | Kosong |
| any other type | Tidak 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.