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
+7.7k Golang : Create zip/ePub file without compression(use Store algorithm)
+32.4k Golang : Convert []string to []byte examples
+16.5k Golang : convert string or integer to big.Int type
+9.6k Golang : Timeout example
+6.2k Golang : Experimenting with the Rejang script
+9k Golang : Sort lines of text example
+8k Golang : Load DSA public key from file example
+14.5k Golang : Recombine chunked files example
+5.4k Golang : Customize scanner.Scanner to treat dash as part of identifier
+15.5k Golang : Accurate and reliable decimal calculations
+14.7k Golang : How to pass map to html template and access the map's elements
+7.4k Golang : Use modern ciphers only in secure connection