Golang : Function as an argument type example
When we need to invoke another function inside a.... let's say outer function, the typical way to do this is to call the desire function inside the outer function. For example, fmt.Sprintf()
:
func int2str(i int) string {
str := fmt.Sprintf("%d", i)
}
In Golang, we are allowed to pass a function as an argument of another function. This can be illustrated by comparing the differences between these two simple programs.
Program 1:
package main
import (
"fmt"
"strconv"
)
func OuterFunc(a int, b int) string {
c := a + b
return strconv.Itoa(c)
}
func main() {
result := OuterFunc(1, 2)
fmt.Println(result)
}
versus
Program 2:
package main
import (
"fmt"
"strconv"
)
var a string = "1"
func OuterFunc(strToInt func(s string) int, b int) string {
c := strToInt(a) + b
return strconv.Itoa(c)
}
func main() {
strToInt := func(s string) int {
num, _ := strconv.Atoi(s)
return num
}
result := OuterFunc(strToInt, 2)
fmt.Println(result)
}
Both programs will produce the same output.
This is also known as anonymous function and you can read a better example at https://gobyexample.com/closures
Now, why use a function as an argument of another function?
The motivation behind this ability is to allow you to specify and pass logic(algorithm) to another function. This is a powerful feature to have in programming language. One clear example that I can think of is how bytes.Map()
function uses this feature to handle the mapping function.
Code from https://www.socketloop.com/references/golang-bytes-map-function-example
package main
import (
"bytes"
"fmt"
)
func main() {
str := []byte("abcxefg")
mapping := func(replacekey rune) rune {
if replacekey == 'x' {
return 'd'
}
return replacekey
}
fmt.Println(string(str))
// now replace x with d
fmt.Println(string(bytes.Map(mapping, str)))
}
Output:
abcxefg
abcdefg
To see the inner working of how bytes.Map()
function works, check out https://golang.org/src/bytes/bytes.go?s=8894:8946#L347
To know more about how Golang treat functions, please read this article - "First Class Functions in Go" by Andrew Gerrand.
Happy coding!
References:
https://golang.org/pkg/bytes/#Map
https://www.socketloop.com/references/golang-bytes-map-function-example
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
+9.1k Golang : cannot assign type int to value (type uint8) in range error
+4.3k Golang : How to deal with configuration data?
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+5.2k Apt-get to install and uninstall Golang
+6.3k Golang : Rot13 and Rot5 algorithms example
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+17.8k Golang : How to make function callback or pass value from function as parameter?
+16.1k Golang : Multi threading or run two processes or more example
+5.1k PageSpeed : Clear or flush cache on web server
+5.2k Golang : Experimental emojis or emoticons icons programming language
+19.8k Golang : Sort and reverse sort a slice of strings
+9.4k Golang : Underscore string example