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
+9k Golang : does not implement flag.Value (missing Set method)
+10.9k Golang : Fix - does not implement sort.Interface (missing Len method)
+16.3k Golang : Delete files by extension
+12.2k Golang : Extract part of string with regular expression
+28.4k Golang : Detect (OS) Operating System
+18.2k Golang : How to get hour, minute, second from time?
+14.9k JavaScript/JQuery : Detect or intercept enter key pressed example
+13.9k Golang : syscall.Socket example
+16.1k Golang : Test floating point numbers not-a-number and infinite example
+6.3k Golang : Totalize or add-up an array or slice example
+7.8k Golang : Get all countries phone codes
+13k Golang : Linear algebra and matrix calculation example