Go course

FunctionsEarly Returns and Guard Clauses

Go

Display

Theme

Functions · Test exercise

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:

  1. negative umur (age) → invalid data, return -1
  2. umur under 3 → free, 0
  3. pelajar (student) is true → 25000 (on any day)
  4. hari (day) is "Sabtu" or "Minggu" (Saturday or Sunday) → 50000
  5. anything else → 40000

Complete hargaTiket(umur int, hari string, pelajar bool) int using guard clauses — no else.

main.go
package main

import "fmt"

func hargaTiket(umur int, hari string, pelajar bool) int {
	// TODO: tulis guard clause sesuai urutan aturan
	return 40000
}

func main() {
	fmt.Println(hargaTiket(20, "Sabtu", false))
	fmt.Println(hargaTiket(2, "Senin", false))
}

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)