Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Passing Functions as Arguments | Functions
Introduction to GoLang
course content

Contenido del Curso

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

bookPassing 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:

go

index

copy
12345678910111213141516
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:

go

index

copy
1234567891011121314151617181920
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)) }
What will be the output of the following program:

What will be the output of the following program:

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 6
We're sorry to hear that something went wrong. What happened?
some-alt