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
+8.3k Golang : Oanda bot with Telegram and RSI example
+19.6k Golang : Close channel after ticker stopped example
+7.5k Golang : Process json data with Jason package
+22.2k Golang : How to run Golang application such as web server in the background or as daemon?
+5.7k Golang : Error handling methods
+6.3k Apt-get to install and uninstall Golang
+12.2k Golang : Split strings into command line arguments
+12.1k Golang : convert(cast) string to integer value
+16.6k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+19.3k Golang : Calculate entire request body length during run time
+7.6k Android Studio : AlertDialog to get user attention example
+8.1k Golang : How To Use Panic and Recover