Higher-Order Functions
This lesson discusses how to use functions as parameters and values.
We'll cover the following...
Function used as a value
Functions can be used as values just like any other value in Go. In the following code, f1
is assigned a value, the function inc1
:
func inc1(x int) int { return x+1 }
f1 := inc1 // f1 := func (x int) int { return x+1 }
Function used as a parameter
Functions can be used as parameters in another function. The passed function can then be called within the body of that function; that is why it is commonly called a callback. To illustrate, here is a simple example:
Press + to interact
package mainimport ("fmt")func main() {callback(1, Add) // function passed as a parameter}func Add(a, b int) {fmt.Printf("The sum of %d and %d is: %d\n", a, b, a + b)}func callback(y int, f func(int, int)) {f(y, 2) // this becomes Add(1, 2)}
To understand the code, look at line 10 at the function header of the function Add
. It takes two parameters a
and b
and prints the sum of the parameters. In the main
, we are just calling the callback
function as: callback(1, Add)
. Here, we have two parameters: the first is ...