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
+10k Golang : How to use if, eq and print properly in html template
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+8.3k Golang : Web(Javascript) to server-side websocket example
+3.9k Unix/Linux : How to pipe/save output of a command to file?
+11k Android Studio : Highlight ImageButton when pressed on example
+13.1k Golang : Find network of an IP address
+27.8k Golang : Get first few and last few characters from string
+5.9k Golang : Takes a plural word and makes it singular
+5.1k PHP : How to check if an array is empty ?
+9.9k Golang : Delay or limit HTTP requests example
+4.4k Unix/Linux/MacOSx : How to remove an environment variable ?
+6.1k Golang : Array mapping with Interface