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
+8.7k Golang : How to join strings?
+5.9k Golang : List all packages and search for certain package
+12k Golang : Convert a rune to unicode style string \u
+6.1k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+9.2k Golang : Write multiple lines or divide string into multiple lines
+10.2k Golang : How to get quoted string into another string?
+26.7k Golang : Encrypt and decrypt data with AES crypto
+21.3k Golang : Create and resolve(read) symbolic links
+8.9k Golang : Find network service name from given port and protocol
+10k Golang : Convert octal value to string to deal with leading zero problem
+7.7k Golang : Error reading timestamp with GORM or SQL driver
+16.5k Golang : Check if a string contains multiple sub-strings in []string?