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
+17.1k Golang : Linked list example
+12k Golang : How to check if a string starts or ends with certain characters or words?
+5.8k Java : Human readable password generator
+31.1k Golang : How to convert(cast) string to IP address?
+3.5k Java : Random alphabets, alpha-numeric or numbers only string generator
+8.3k Golang : Convert(cast) []byte to io.Reader type
+7.1k Golang : alternative to os.Exit() function
+35.7k Golang : Converting a negative number to positive number
+14.1k Golang : Send email with attachment(RFC2822) using Gmail API example
+8.9k Golang : How to check if a string with spaces in between is numeric?
+5.4k Fix fatal error: evacuation not done in time problem
+11.3k CodeIgniter : Import Linkedin data