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
+6k Golang : Takes a plural word and makes it singular
+9.5k Golang : Create matrix with Gonum Matrix package example
+12.2k Golang : reCAPTCHA example
+15.5k Golang : Gzip file example
+20.7k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+26.6k Get file path of temporary file in Go
+11.5k Golang : Exit, terminating or aborting a program
+28.6k Golang : How to get HTTP request header information?
+5.6k Nginx : Password protect a directory/folder
+6.5k Golang : Example of how to detect which type of script a word belongs to
+9.7k Golang : Create Temporary File
+11.3k Golang : Search and extract certain XML data example