Skip to content

Pass Behavior as a Value

The Course
•
24 min study

In Go a function is a value, just like a number or a string. You can store it in a variable, pass it to another function and return it from one. That lets you separate what to do with each item from how to visit the items. You have already used this once: in the intermediate task queue, slices.SortFunc took a comparison function. The sort algorithm stayed the same, and the function you passed decided the order. This week's project uses the same idea to hand parsing work to several goroutines, so it is worth getting comfortable with function values first.

A function type is written like a function signature without a name. func(int) int is the type of any function that takes one int and returns one int. A parameter of that type accepts a named function, such as double, or a function literal written in place.

Predict and run

apply calls f once for each value and collects the results. What do the two lines print?

Predict, then run Go
package main

import (
	"fmt"
)

func apply(values []int, f func(int) int) []int {
	result := make([]int, len(values))
	for i, v := range values {
		result[i] = f(v)
	}
	return result
}

func double(n int) int {
	return n * 2
}

func main() {
	fmt.Println(apply([]int{1, 2, 3}, double))
	fmt.Println(apply([]int{1, 2, 3}, func(n int) int { return n + 10 }))
}
Check your prediction
Text
[2 4 6]
[11 12 13]

Notice that double is passed without parentheses. double is the function value; double(2) would call it and pass the result, which is an int, not a function. Change the literal so it squares each number, and predict the output first.

Closures keep their variables

A function literal can use variables from the code around it. When it does, it is called a closure, and it keeps those variables alive for as long as the closure exists. Each call to counter below creates a fresh count and a fresh closure that owns it.

Two independent counters Go
package main

import (
	"fmt"
)

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func main() {
	next := counter()
	fmt.Println(next(), next(), next())
	other := counter()
	fmt.Println(other(), next())
}
Text
1 2 3
1 4

count is not copied into the closure. The closure refers to the variable itself, so every call to next sees the value the previous call left. other has its own count, which is why it starts again at 1 while next carries on to 4.

Each loop iteration has its own variable

Closures created in a loop capture that iteration's variables. Since Go 1.22, every iteration of a for loop gets new copies of the loop variables, so each closure below remembers a different name. Older Go versions shared one variable across iterations, and this program printed drill twice; you may still see workarounds for that in older code.

Closures made in a loop Go
package main

import (
	"fmt"
)

func main() {
	var printers []func()
	for _, name := range []string{"tent", "drill"} {
		printers = append(printers, func() { fmt.Println("Item:", name) })
	}
	for _, show := range printers {
		show()
	}
}
Text
Item: tent
Item: drill
Name the function type when it repeats

If the same function type appears in several signatures, give it a name, such as type Rule func(int) bool. The code reads better, and you can attach documentation to the name. For a single use, the plain func(int) bool is clearer.

Practice

Exercise

Your turn

Write countWhere(values []int, keep func(int) bool) int, which counts the values for which keep returns true. Then write atLeast(limit int) func(int) bool, which returns a closure that reports whether a value is at least limit. Count the values in 5, 20, 35 and 50 that are at least 20, and then at least 50.

The output should be:

Text
3
1
Your working space Go
package main

func main() {
	// Write countWhere and atLeast, then call them.
}
Hint 1: the idea

countWhere does not know the rule. It only loops and asks keep about each value. atLeast builds a rule by capturing limit.

Hint 2: a first step

Write countWhere first and try it with a function literal written at the call, such as one that keeps even numbers. Then have atLeast return a function literal whose body compares its parameter with limit, the value it captures.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func countWhere(values []int, keep func(int) bool) int {
	count := 0
	for _, v := range values {
		if keep(v) {
			count++
		}
	}
	return count
}

func atLeast(limit int) func(int) bool {
	return func(n int) bool { return n >= limit }
}

func main() {
	values := []int{5, 20, 35, 50}
	fmt.Println(countWhere(values, atLeast(20)))
	fmt.Println(countWhere(values, atLeast(50)))
}
Text
3
1

Each call to atLeast captures a different limit, so the same countWhere loop answers two questions. Including 20 and 50 themselves checks that the rule uses >= rather than >.

Was this article helpful?

Your response is saved on this device.