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
+5k Golang : The Tao of importing package
+29.1k Golang : How to create new XML file ?
+20.9k Golang : Convert(cast) string to rune and back to string example
+15.1k Golang : invalid character ',' looking for beginning of value
+23k Golang : Get ASCII code from a key press(cross-platform) example
+35.6k Golang : Save image to PNG, JPEG or GIF format.
+16.1k Golang : Find out mime type from bytes in buffer
+8.7k Golang : Inject/embed Javascript before sending out to browser example
+7k Golang : Dealing with postal or zip code example
+29.5k Golang : Get time.Duration in year, month, week or day
+5.7k Golang : List all packages and search for certain package
+11.3k Golang : Handle API query by curl with Gorilla Queries example