Tagless switch and fallthrough
switch without an expression
If you write switch without a value after it, each case holds its own bool condition. Go runs the first case that's true. It's a neat way to write a long if ... else if chain:
switch {
case suhu >= 38:
fmt.Println("Demam tinggi")
case suhu >= 37.5:
fmt.Println("Demam ringan")
case suhu < 35:
fmt.Println("Hipotermia")
default:
fmt.Println("Normal")
}
This checks a body temperature (suhu) for high fever, mild fever, hypothermia, or normal.
The order of the cases matters: put the strictest condition first. If suhu >= 37.5 came before suhu >= 38, a high fever would never be detected.
fallthrough
By default, switch stops once a case finishes. The fallthrough keyword forces Go to also run the body of the next case without checking its condition:
switch paket {
case "premium":
fmt.Println("+ akses lounge")
fallthrough
case "reguler":
fmt.Println("+ bagasi 20 kg")
}
// paket "premium" mencetak kedua baris
// paket "reguler" hanya mencetak baris kedua
The "premium" package prints both lines (lounge access and 20 kg baggage), while "reguler" only prints the second one.
fallthrough is rarely used and easily confusing. Only reach for it when you really need it.
Task
An RPG gives players a title based on their experience points (XP). Complete gelarPemain(xp int) string using a switch without an expression:
| Condition | Title |
|---|---|
negative xp | "tidak valid" |
xp >= 10000 | "Legenda" |
xp >= 5000 | "Pahlawan" |
xp >= 1000 | "Petualang" |
| anything else | "Pemula" |
(That's "invalid", "Legend", "Hero", "Adventurer", and "Beginner".)
Example: gelarPemain(5000) → "Pahlawan", gelarPemain(999) → "Pemula".