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.1k Golang : Detect number of active displays and the display's resolution
+4.1k Golang : Constant and variable names in native language
+4.4k Python : Delay with time.sleep() function example
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+21.4k Golang : simulate tail -f or read last line from log file example
+7.2k How to show different content from website server when AdBlock is detected?
+40.8k Golang : Get hardware information such as disk, memory and CPU usage
+12.9k Golang : Convert IP version 6 address to integer or decimal number
+7k Golang : Add build version and other information in executables
+33.5k Golang : Upload and download file to/from AWS S3
+11.2k Golang : How to display image file or expose CSS, JS files from localhost?