Golang : How to make function callback or pass value from function as parameter?
There are times we need to evaluate a function and pass the evaluated value as parameter to a function. In Golang, this is known as function callback. Below is an example of function callback in action.
package main
import "fmt"
func square(f func(int) int, x int) int {
return f(x * x)
}
func main() {
// call back functions for 2 times
fmt.Printf("%v\n", square(func(i int) int {
return i * i
}, 2))
}
Sample output :
16
Reference :
https://www.socketloop.com/tutorials/golang-squaring-elements-in-array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+17.2k Golang : Get input from keyboard
+23.6k Golang : Get ASCII code from a key press(cross-platform) example
+22.6k Golang : How to read JPG(JPEG), GIF and PNG files ?
+13.1k Swift : Convert (cast) Int to String ?
+17.1k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+12.3k Golang : Pagination with go-paginator configuration example
+20.5k Golang : Determine if directory is empty with os.File.Readdir() function
+7.6k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+6k Golang : Generate multiplication table from an integer example
+29.7k Golang : Saving(serializing) and reading file with GOB
+14.5k Golang : Parsing or breaking down URL
+8k Golang : Ways to recover memory during run time.