Functions as Values
In Go, functions are ordinary values (first-class). You can store a function in a variable and pass it as an argument to another function.
func kuadrat(x int) int {
return x * x
}
func main() {
f := kuadrat // simpan fungsi di variabel (tanpa tanda kurung!)
fmt.Println(f(4)) // 16
}
Notice that f := kuadrat stores the function in a variable — with no parentheses!
Function types
A function's type is defined by its parameters and return values. kuadrat above has the type func(int) int. You can use that type as a parameter type:
func olah(x int, operasi func(int) int) int {
return operasi(x)
}
olah(5, kuadrat) // 25
Anonymous functions
You can also write a function inline without a name (an anonymous function), which is handy for one-off logic:
hasil := olah(5, func(x int) int {
return x + 100
})
fmt.Println(hasil) // 105
This pattern keeps your code flexible: olah doesn't need to know which operation it's running — the caller decides.
Task
An online store app has a few kinds of promos. Complete three functions:
diskonMember(harga int) int— a 10% member discount, so the result isharga * 90 / 100.potongan5000(harga int) int— take off5000, but the result can't go negative (ifharga < 5000, return0).terapkanPromo(harga int, promo func(int) int) int— callpromowithhargaand return the result.
Example: terapkanPromo(100000, diskonMember) → 90000.
The tests will also call terapkanPromo with anonymous functions of their own.