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.6k Golang : Convert(cast) io.Reader type to string
+9.7k Golang : Load ASN1 encoded DSA public key PEM file example
+20.1k Golang : Determine if directory is empty with os.File.Readdir() function
+13k Golang : Convert(cast) uintptr to string example
+9.6k Golang : Sort and reverse sort a slice of floats
+21.3k Curl usage examples with Golang
+5.5k Python : Print unicode escape characters and string
+11.5k SSL : The certificate is not trusted because no issuer chain was provided
+4.6k Golang : How to pass data between controllers with JSON Web Token
+21.5k Golang : Encrypt and decrypt data with TripleDES
+9.3k Golang : Generate EAN barcode
+14k Javascript : Prompt confirmation before exit