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
+12k Golang : Calculate elapsed years or months since a date
+10k Golang : How to pipe input data to executing child process?
+18.8k nginx: [emerg] unknown directive "passenger_enabled"
+7.6k Golang : Combine slices but preserve order example
+27.9k Golang : missing Git command
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+9.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+11.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.9k Golang : constant 20013 overflows byte error message
+53.2k Golang : Unmarshal JSON from http response
+13.6k Golang : Missing Bazaar command
+7k Golang : Variadic function arguments sanity check example