Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Passing Functions as Arguments | Section
Getting Started with Go

bookPassing Functions as Arguments

Swipe um das Menü anzuzeigen

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:

func myFunc(param1 datatype, param2 datatype, ...) optional_return_type {
      // Code
      // Optional return statement
}

We use the following syntax to specify the data type of the parameter when passing it to a function:

func(datatype, datatype, …) return_datatype

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

index.go

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:

index.go

index.go

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)) }
question mark

What will be the output of the following program:

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 32

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 32
some-alt