Using Anonymous Functions as Callback Functions
Earlier, we assigned an anonymous function to a variable. Similarly, we can also use an anonymous function as an argument to a function. In this case, the anonymous function can be referred to as a callback function.
Let's look at an example:
package main
import (
"fmt"
"math"
)
// Traverse the elements of a slice and process each value using a callback function
func visit(lst []float64, f func(float64)) {
for _, value := range lst {
f(value)
}
}
func main() {
// Sum each element
arr := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9}
visit(arr, func(v float64) {
fmt.Printf("Sum:%.0f ", v+v)
})
println()
// Calculate the product of each element
visit(arr, func(v float64) {
fmt.Printf("Product:%.0f ", v*v)
})
println()
// Calculate the square of each element
visit(arr, func(v float64) {
v = math.Pow(v, 2)
fmt.Printf("Square:%.0f ", v)
})
println()
}
Sum:2 Sum:4 Sum:6 Sum:8 Sum:10 Sum:12 Sum:14 Sum:16 Sum:18
Product:1 Product:4 Product:9 Product:16 Product:25 Product:36 Product:49 Product:64 Product:81
Square:1 Square:4 Square:9 Square:16 Square:25 Square:36 Square:49 Square:64 Square:81
In this program, we first create a visit
function with a callback that iterates over a given slice list and passes the values to the callback function for processing.
Inside the main
function, we use an anonymous function to define three different callbacks to calculate the sum, product, and square of each element.
As you can see, callback functions are very flexible. They act as intermediate functions, and different anonymous functions can produce different behaviors within the callback function.