Course Content
Introduction to GoLang
Introduction to GoLang
Passing Functions as Arguments
Another useful feature is the ability to pass functions as arguments to other functions.
As a reminder, the fundamental syntax of a function with parameters is as follows:
We use the following syntax to specify the data type of the parameter when passing it to a function:
The func
keyword is followed by comma-separated data types for the parameters of that function within parentheses. Additionally, we specify the return data type for the expected function or set of functions, if applicable.
An example can help illustrate this concept:
index
package main import "fmt" func nTimes(n int, msg string) { for i := 0; i < n; i++ { fmt.Println(msg) } } func printFiveTimes(msg string, show func(int, string)) { show(5, "Hello World") } func main() { printFiveTimes("HelloWorld", nTimes) }
In the example above, we pass a function named nTimes
as an argument to the printFiveTimes
function. The data type for the show
parameter in the definition of the printFiveTimes
function is func(int, string)
, which corresponds to the definition of the nTimes
function, i.e., nTimes(n int, msg string)
.
Now, let's take a look at an example of a function with a return value:
index
package main import "fmt" // A factorial is the product of all the numbers from 1 up till n // For-example factorial of 5 is 1x2x3x4x5, which is 120 func factorial(n int) int { var result int = 1; for i := 2; i <= n; i++ { result *= i } return result } func eval(n int, oper func(int) int) int { return oper(n) } func main() { fmt.Println(eval(5, factorial)) }
Thanks for your feedback!