switch
When you're comparing one value against many possibilities, switch is tidier than a chain of if ... else if:
switch metode {
case "tunai":
fmt.Println("Bayar di kasir")
case "qris":
fmt.Println("Pindai kode QR")
case "kartu":
fmt.Println("Masukkan kartu ke mesin EDC")
default:
fmt.Println("Metode tidak dikenal")
}
Here a payment method of cash ("tunai"), QRIS, or card ("kartu") each prints its own instruction, and anything else prints "Metode tidak dikenal" ("unknown method").
Key things to know about switch in Go:
- Each
casestops automatically when it's done. You don't need to (and usually don't) writebreaklike in C or Java. defaultruns when nocasematches. It's optional.- A single
casecan list several values, separated by commas:
switch hari {
case "Sabtu", "Minggu":
fmt.Println("Akhir pekan")
default:
fmt.Println("Hari kerja")
}
(Saturday and Sunday print "weekend"; every other day prints "weekday".)
switch also supports an init statement, just like if: switch kode := ambilKode(); kode { ... }.
Task
The "Senja" coffee shop sells drinks in three sizes. Complete these two functions using switch:
-
hargaUkuran(ukuran string) int(price by size)ukuran price "S"15000"M"18000"L"22000anything else 0 -
jenisMenu(menu string) string(menu category)"espresso","latte", or"cappuccino"→"kopi"(coffee)"teh tarik"or"matcha"→"non-kopi"(non-coffee)- anything else →
"tidak tersedia"(not available)