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

Passing Functions as ArgumentsPassing 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.go

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.go

What will be the output of the following program:

Selecione a resposta correta

Tudo estava claro?

Seção 4. Capítulo 6
course content

Conteúdo do Curso

Introduction to GoLang

Passing Functions as ArgumentsPassing 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.go

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.go

What will be the output of the following program:

Selecione a resposta correta

Tudo estava claro?

Seção 4. Capítulo 6
some-alt