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
+17.3k Golang : Multi threading or run two processes or more example
+34.8k Golang : Smarter Error Handling with strings.Contains()
+16.1k Golang : Loop each day of the current month example
+5.3k Golang *File points to a file or directory ?
+9.2k Golang : Generate EAN barcode
+13.4k Golang : Qt progress dialog example
+8.2k Useful methods to access blocked websites
+6.8k Golang : Decode XML data from RSS feed
+14.9k Golang : Search folders for file recursively with wildcard support
+14.3k Golang : How to check if your program is running in a terminal
+14.4k Golang : Convert(cast) int to float example
+9.5k Golang : Sort and reverse sort a slice of floats