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
+16k Golang : Test floating point numbers not-a-number and infinite example
+29.8k Golang : How to verify uploaded file is image or allowed file types
+12.2k Golang : Exit, terminating or aborting a program
+10.2k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+34.6k Golang : Upload and download file to/from AWS S3
+14.5k Golang : How to check for empty array string or string?
+8.4k Android Studio : Image button and button example
+6.1k Golang : Handling image beyond OpenCV video capture boundary
+5.3k Golang : Shortening import identifier
+17k Golang : Multi threading or run two processes or more example
+31k Golang : Get local IP and MAC address
+14.7k Golang : Accurate and reliable decimal calculations