Go course

FunctionsFunctions as Values

Go

Display

Theme

Functions · Test exercise

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:

  1. diskonMember(harga int) int — a 10% member discount, so the result is harga * 90 / 100.
  2. potongan5000(harga int) int — take off 5000, but the result can't go negative (if harga < 5000, return 0).
  3. terapkanPromo(harga int, promo func(int) int) int — call promo with harga and return the result.

Example: terapkanPromo(100000, diskonMember) → 90000.

The tests will also call terapkanPromo with anonymous functions of their own.

main.go
package main

import "fmt"

func diskonMember(harga int) int {
	// TODO: potongan 10%
	return harga
}

func potongan5000(harga int) int {
	// TODO: kurangi 5000, minimal 0
	return harga
}

func terapkanPromo(harga int, promo func(int) int) int {
	// TODO: panggil promo
	return harga
}

func main() {
	fmt.Println(terapkanPromo(100000, diskonMember))
	fmt.Println(terapkanPromo(3000, potongan5000))
}

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)