Go course

Conditionalsswitch

Go

Display

Theme

Conditionals · Test exercise

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 case stops automatically when it's done. You don't need to (and usually don't) write break like in C or Java.
  • default runs when no case matches. It's optional.
  • A single case can 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:

  1. hargaUkuran(ukuran string) int (price by size)

    ukuranprice
    "S"15000
    "M"18000
    "L"22000
    anything else0
  2. 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)
main.go
package main

import "fmt"

func hargaUkuran(ukuran string) int {
	// TODO: gunakan switch
	return 0
}

func jenisMenu(menu string) string {
	// TODO: gunakan switch dengan beberapa nilai dalam satu case
	return "tidak tersedia"
}

func main() {
	fmt.Println("Harga ukuran M:", hargaUkuran("M"))
	fmt.Println("latte adalah", jenisMenu("latte"))
}

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)