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
+15.2k Golang : ROT47 (Caesar cipher by 47 characters) example
+4.8k Golang : Constant and variable names in native language
+16.7k Golang : Capture stdout of a child process and act according to the result
+13.4k Golang : Activate web camera and broadcast out base64 encoded images
+6.4k Golang : How to validate ISBN?
+13.4k Golang : Query string with space symbol %20 in between
+19.3k Golang : Close channel after ticker stopped example
+11.8k Golang : Save webcamera frames to video file
+7.2k Golang : Create zip/ePub file without compression(use Store algorithm)
+13.5k Golang : Tutorial on loading GOB and PEM files
+5.9k Java : Human readable password generator
+9.3k Golang : Changing a RGBA image number of channels with OpenCV