Use functions as values
Use functions as values
Functions are values in Go. A variable of type func(int) int can hold a function taking one int and returning one int. You can assign a named function without parentheses, call it through the variable, or pass it to another function.
package main
import "fmt"
func triple(n int) int { return n * 3 }func main() { var operation func(int) int = triple fmt.Println(operation(4))}triple refers to the function itself; triple(4) calls it and produces an integer. The function value must have a compatible signature.
Pass a function to another function
package main
import "fmt"
func apply(n int, transform func(int) int) int { return transform(n) }func main() { square := func(n int) int { return n * n } fmt.Println(apply(5, square))}The function literal has no name. It is assigned to square and passed as a callback (a function supplied for another function to call). The zero value of a function variable is nil; calling nil causes a panic. Check it before calling if it may be absent.
Try it locally
Write applyTwice(n int, f func(int) int) int applying f twice. Pass a function literal that adds 3; print results for 1 and -6.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 07: Use functions as values
Check the lesson objective before moving on.
Which expression denotes the function itself?
What happens if a nil function value is called?