Go Anonymous Function
An anonymous function is a function that does not have any name associated while declaring it. Anonymous functions can be used as an argument to other functions.
A Quick Example
package main
import "fmt"
var greet = func() {
fmt.Print("Welcome to Go Programming !!!")
}
func main() {
greet()
}
Output
Welcome to Go Programming !!!
Sometimes, when writing a program, we want to define a small function that is only going to be used once (for example, as a parameter to a sorting function). In such a case, it would add unnecessary clutter to the program to give the function a name, we rather want to define it as a lambda, that is, an anonymous function.
Syntax of anonymous functions
The syntax of an anonymous function is as follows:
func (parameters) (returnType) {
// function body
}
It is similar to the syntax of a normal function, except that there is no identifier after the func
keyword.
Iterate a function a certain number of times
As an example, let's consider a function that takes three arguments:
- an integer
x
, - a function
f
that takes an integer as an argument and returns an integer, - an integer
n
: the number of times we want to applyf
tox
.
In Go,
func iterate(x int, f func(int) int, n int) int {
for i := 0; i < n; i++ {
x = f(x)
}
return x
}
Now, we can use an anonymous function as the second argument to iterate
:
func main() {
fmt.Println(iterate(2, func(x int) int { return x * x }, 3))
}
This snippet prints 256
(that is ((2^2)^2)^2).
Sort an array of integers given a comparison function
A more realistic example is to sort an array of integers given a comparison function. As above, we start by defining a function that takes another function as an argument:
func sort(a []int, less func(int, int) bool) {
for i, _ := range a {
for j, _ := range a {
if less(a[j], a[i]) {
a[i], a[j] = a[j], a[i]
}
}
}
}
This algorithm is naive, but it is easy to understand.
Then we can sort an array of integers using a variety of comparison functions:
func main() {
a := []int{45, 9, 45, 0, 9, 1, 4, 3}
sort(a, func(x, y int) bool { return x < y })
fmt.Println(a)
sort(a, func(x, y int) bool { return x > y })
fmt.Println(a)
sort(a, func(x, y int) bool { return x%10 < y%10 })
fmt.Println(a)
}
The third example sorts the array by the last digit of the numbers.