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.3k Golang : Reverse text lines or flip line order example
+9.6k Golang : Changing a RGBA image number of channels with OpenCV
+7.4k Golang : File system scanning
+8.7k Android Studio : Import third-party library or package into Gradle Scripts
+26.9k Golang : Convert file content into array of bytes
+13.1k Golang : Get terminal width and height example
+7.2k Golang : Validate credit card example
+10k Golang : Sort and reverse sort a slice of integers
+5.5k Golang : What is StructTag and how to get StructTag's value?
+18.1k Golang : Qt image viewer example
+29.6k Golang : How to create new XML file ?
+11.3k Google Maps URL parameters configuration