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.1k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+31.8k Golang : Convert []string to []byte examples
+10.2k Golang : Get local time and equivalent time in different time zone
+16.1k Golang : How to implement two-factor authentication?
+9.7k Golang : Test a slice of integers for odd and even numbers
+6.8k Golang : Squaring elements in array
+10.3k Golang : Flip coin example
+20.7k Golang : Create and resolve(read) symbolic links
+10.7k Google Maps URL parameters configuration
+6.8k Golang : Transform lisp or spinal case to Pascal case example
+16.5k Golang : Capture stdout of a child process and act according to the result
+19.3k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader