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
+13.8k Golang : Image to ASCII art example
+12.1k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+3.5k Golang : Fix go-cron set time not working issue
+11.6k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+55.4k Golang : Unmarshal JSON from http response
+10.7k Golang : Bubble sort example
+14.1k Golang : convert rune to unicode hexadecimal value and back to rune character
+19.8k Golang : Archive directory with tar and gzip
+8.7k Golang : Another camera capture GUI application with GTK and OpenCV
+7.1k Web : How to see your website from different countries?
+5.8k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+28k Golang : Decode/unmarshal unknown JSON data type with map[string]interface