Early Returns and Guard Clauses
return stops a function immediately. You can use that to handle special cases at the start of a function and get out early. This pattern is called a guard clause.
Compare these two versions:
// Bersarang: logika utama tenggelam di dalam if
func ongkir(berat int, kota string) int {
if berat > 0 {
if kota != "" {
if kota == "Jakarta" {
return 10000
} else {
return 18000
}
} else {
return -1
}
} else {
return -1
}
}
// Guard clause: kasus tidak valid disingkirkan dulu
func ongkir(berat int, kota string) int {
if berat <= 0 {
return -1
}
if kota == "" {
return -1
}
if kota == "Jakarta" {
return 10000
}
return 18000
}
In the first, nested version the main logic is buried inside the ifs; in the guard clause version the invalid cases get cleared out first. The second version is flatter and easier to read: each if handles one case and then returns. The "normal" path sits at the very bottom with no extra indentation. This is the style Go programmers commonly use.
Tip: after an if block that ends in return, you don't need an else.
Task
The "Dunia Ceria" amusement park sets ticket prices with these rules, checked in order:
- negative
umur(age) → invalid data, return-1 umurunder3→ free,0pelajar(student) istrue→25000(on any day)hari(day) is"Sabtu"or"Minggu"(Saturday or Sunday) →50000- anything else →
40000
Complete hargaTiket(umur int, hari string, pelajar bool) int using guard clauses — no else.