Go course

Conditionalsif with an Init Statement

Go

Display

Theme

Conditionals · Test exercise

if with an Init Statement

In Go, an if can start with a short statement (usually :=) before the condition, separated by a semicolon:

if sisa := stok - dipesan; sisa < 0 {
	fmt.Println("Stok kurang", -sisa, "unit")
} else {
	fmt.Println("Sisa stok:", sisa)
}

The variable sisa (what's left in stock) only lives inside that if (including its else if and else). Outside the block, sisa doesn't exist:

if sisa := stok - dipesan; sisa < 0 {
	// ...
}
fmt.Println(sisa) // ERROR: undefined: sisa

This pattern keeps temporary variables from "leaking" into the rest of the function. You'll see it a lot later on when handling errors:

if err := simpan(data); err != nil {
	// tangani error
}

Task

A mall parking garage calculates its fee like this:

  • the base rate is 3000 per hour, so the initial fee = jam * 3000;
  • if the initial fee is more than 20000, the visitor only pays 20000 (the daily maximum);
  • if jam (hours) is less than or equal to 0, the fee is 0.

Complete biayaParkir(jam int) int. Use an if with an init statement to calculate the initial fee, for example if biaya := jam * 3000; biaya > 20000 { ... }.

Example: biayaParkir(2) → 6000, biayaParkir(9) → 20000.

main.go
package main

import "fmt"

func biayaParkir(jam int) int {
	// TODO: tangani jam <= 0, lalu gunakan if dengan pernyataan awal
	return jam * 3000
}

func main() {
	fmt.Println("Parkir 2 jam:", biayaParkir(2))
	fmt.Println("Parkir 9 jam:", biayaParkir(9))
}

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)