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
+14.9k Golang : How to check if input from os.Args is integer?
+8.3k Golang : Read file with ioutil
+3.9k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+14.4k Golang : How to convert(cast) IP address to string?
+13.5k Golang : Rename directory
+4.9k Unix/Linux : How to open tar.gz file ?
+61.5k Golang : Convert HTTP Response body to string
+23.6k Golang : convert rune to integer value
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+8.2k Golang : Timeout example
+31.3k Golang : Regular Expression for alphanumeric and underscore
+7.4k Golang : Convert word to its plural form example