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
+22.9k Golang : Find biggest/largest number in array
+4.5k Javascript : How to loop over and parse JSON data?
+18.7k Golang : Reset or rewind io.Reader or io.Writer
+17.4k Golang : Example for RSA package functions
+4k Google : Block or disable caching of your website content
+7.9k Golang : GMail API create and send draft with simple upload attachment example
+7.7k Golang : Gaussian blur on image and camera video feed examples
+21.3k Generate checksum for a file in Go
+9.7k Golang : Replace a parameter's value inside a configuration file example
+10.9k Golang : Convert a rune to unicode style string \u
+5.3k Golang : Extract sub-strings
+34.2k Golang : How to split or chunking a file to smaller pieces?