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
3000per hour, so the initial fee =jam * 3000; - if the initial fee is more than
20000, the visitor only pays20000(the daily maximum); - if
jam(hours) is less than or equal to0, the fee is0.
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.