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
+32.2k Golang : Create x509 certificate, private and public keys
+6.8k Golang : Get today's weekday name and calculate target day distance example
+6.5k Golang : Handling Yes No Quit query input
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+6.9k Golang : Regular Expression find string example
+6.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+9.1k Golang : Convert file content to Hex
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+10k Golang : Create S3 bucket with official aws-sdk-go package
+12k Golang : Count number of runes in string
+7.9k Golang : HTTP Routing with Goji example
+8.2k Golang : does not implement flag.Value (missing Set method)