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
+12.3k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+11.7k Golang : How to parse plain email text and process email header?
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+6.3k Unix/Linux : How to get own IP address ?
+7.1k Golang : Process json data with Jason package
+7.9k Golang : HTTP Server Example
+6.4k Golang : Check if password length meet the requirement
+6.9k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+10.7k Golang : Simple image viewer with Go-GTK
+16.1k Golang : Check if a string contains multiple sub-strings in []string?