Callbacks
Because functions are values they are easy to pass to functions, from where theycan be used as callbacks. First define a function that does “something” with aninteger value:
func printit(x int) {
fmt.Printf("%v\n", x)
}
This function does not return a value and just prints its argument. Thesignature of this function is: func printit(int)
,or without the function name: func(int)
. To create a new function that usesthis one as a callback we need to use this signature:
func callback(y int, f func(int)) {
f(y)
}
Here we create a new function that takes two parameters: y int
, i.e. just anint
and f func(int)
, i.e. a function that takes an int and returns nothing.The parameter f
is the variable holding that function. It can be used as anyother function, and we execute the function on line 2 with the parameter y
:f(y)