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
+9.9k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+26.7k Golang : Convert file content into array of bytes
+7.6k Gogland : Where to put source code files in package directory for rookie
+5.6k Golang : Detect words using using consecutive letters in a given string
+10.4k Golang : Meaning of omitempty in struct's field tag
+16k Golang : How to reverse elements order in map ?
+16.2k Golang : convert string or integer to big.Int type
+30.3k Golang : How to verify uploaded file is image or allowed file types
+37.4k Upload multiple files with Go
+32.3k Golang : Math pow(the power of x^y) example
+27.4k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+7.6k Golang : get the current working directory of a running program