Go Functions as Values
Functions as values are functions stored, passed, and returned like other values. A variable of a function type can hold any function with the same parameter and result types.
A function passed as a parameter
apply takes a function and a number. It calls the function on the number.
package main
import "fmt"
func double(n int) int {
return n * 2
}
func apply(f func(int) int, v int) int {
return f(v)
}
func main() {
fmt.Println(apply(double, 21))
}Functions stored in a slice and a map
The slice holds two functions in order. The map holds the same two functions under keys.
package main
import "fmt"
func addOne(n int) int {
return n + 1
}
func triple(n int) int {
return n * 3
}
func main() {
steps := []func(int) int{addOne, triple}
fmt.Println(steps[0](10))
fmt.Println(steps[1](10))
ops := map[string]func(int) int{
"add": addOne,
"triple": triple,
}
fmt.Println(ops["add"](5))
fmt.Println(ops["triple"](5))
}A function returning a function
multiplier returns a closure for one factor. The returned function multiplies by that factor.
package main
import "fmt"
func multiplier(factor int) func(int) int {
return func(n int) int {
return n * factor
}
}
func main() {
timesThree := multiplier(3)
fmt.Println(timesThree(7))
fmt.Println(multiplier(10)(2))
}Example
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func subtract(a int, b int) int {
return a - b
}
func multiply(a int, b int) int {
return a * b
}
func main() {
ops := map[string]func(int, int) int{
"add": add,
"sub": subtract,
"mul": multiply,
}
fmt.Println(ops["add"](8, 3))
fmt.Println(ops["sub"](8, 3))
fmt.Println(ops["mul"](8, 3))
}Key points
- A function type names the parameter types and the result type.
- Use a parameter of a function type to pass a function into another function.
- A slice can hold function values in order.
- A map can hold function values under keys.
- A stored function is called by index from a slice or by key from a map.
- A function can return a function value as its result.
- Calling a stored function uses the same call shape as calling a named function.
In this example, the map holds three operation functions under short keys. The add key runs add on 8 and 3 and prints 11. The sub key runs subtract and prints 5. The mul key runs multiply and prints 24.
Note
A function value is nil until a function is assigned to it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Go Playground
Exercise
Which line declares a parameter that holds a function?