Essential Go Functions  Edit on GitHub      File Issue

Variables of function type

Functions are first-class values in Go:

Assigning functions to variables

// intOp is a variable whose type is function that takes
// 2 integers as arguments and returns an integer
var intOp func(int, int) int

func intAdd(a, b int) int {
	return a + b
}

func main() {
	intOp = intAdd
	fmt.Printf("intOp(2, 3) = %d\n", intOp(2, 3))

	// we can assign literal functions as well
	intOp = func(a, b int) int {
		return a * b
	}
	fmt.Printf("intOp(2, 3) = %d\n", intOp(2, 3))
}
intOp(2, 3) = 5
intOp(2, 3) = 6

Using variables for functions can be used when testing for mocking.

During real operation a variable points to a real function.

During tests a variable points to a function that mocks the functionality.

Passing function as function arguments

func funcAdd(a, b int) int {
	return a + b
}

func runFunc(a, b int, intOp func(int, int) int) {
	fmt.Printf("intOp(%d, %d) = %d\n", a, b, intOp(a, b))
}

func main() {
	runFunc(2, 3, funcAdd)

	// we can pass literal functions as well
	runFunc(2, 3, func(a, b int) int {
		return a * b
	})
}
intOp(2, 3) = 5
intOp(2, 3) = 6

Common uses of passing functions:

  ↑ ↓ to navigate     ↵ to select     Esc to close