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
+32.3k Golang : How to check if a date is within certain range?
+7.6k Golang : Get all countries phone codes
+11.1k CodeIgniter : Import Linkedin data
+4.3k Chrome : How to block socketloop.com links in Google SERP?
+11.5k Golang : Clean formatting/indenting or pretty print JSON result
+14k Golang : Reset buffer example
+7.5k Golang : Handle Palindrome string with case sensitivity and unicode
+13.1k Golang : Read XML elements data with xml.CharData example
+30.3k Golang : Calculate percentage change of two values
+17k Golang : Clone with pointer and modify value
+5k Golang : Generate Interleaved 2 inch by 5 inch barcode