Functions That Accept Other Functions as Parameters
Let’s learn about functions that accept other functions as parameters.
We'll cover the following
Functions can accept other functions as parameters. The best example of a function that accepts another function as an argument can be found in the sort
package. We can provide the sort.Slice()
function with another function as an argument that specifies the way sorting is implemented.
Signature of sort.Slice()
The signature of sort.Slice()
is func Slice(slice interface{}, less func(i, j int) bool)
. This means the following:
The
sort.Slice()
function does not return any data—the slice variable is modified insidesort.Slice()
.The
sort.Slice()
function requires two arguments, a slice of typeinterface{}
and another function.The function parameter of
sort.Slice()
is namedless
and should have thefunc(i, j int) bool
signature. While there is no need for us to name the anonymous function that we pass tosort.Slice()
, the nameless
is required because Go requires all function parameters to have a name.The
i
andj
parameters ofless
are indexes of theslice
parameter.
The sort.SliceIsSorted()
function
Similarly, there is another function in the sort
package named sort.SliceIsSorted()
that is defined as func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool
. This function returns a bool
value and checks whether the slice
parameter is sorted according to the rules of the second parameter, which is a function.
Note: We are not obliged to use an anonymous function in either
sort.Slice()
orsort.SliceIsSorted()
. We can define a regular function with the required signature and use that. However, using an anonymous function is more convenient.
Coding example
The use of both sort.Slice()
and sort.SliceIsSorted()
is illustrated in the Go program that follows—the name of the source file is sorting.go
:
Get hands-on with 1400+ tech skills courses.