How to Pass Function as Parameter in Golang

In Go, functions are first-class citizens, meaning you can pass them around like any other value. When passing a function as a parameter, you define the type of the function parameter based on the signature of the function you want to pass.

To pass a function as a parameter to another function, define the parameter type as a function signature”. Function signatures describe a function’s input and output types without specifying its implementation.

Here’s a step-by-step guide to passing a function as a parameter in Go:

Step 1: Define the Function Type

Start by defining the type of function you want to pass as an argument. For example, if you’re going to pass a function that takes two integers as arguments and returns an integer, you would define the function type as:

type MyFunctionType func(int, int) int

Step 2: Pass the Function as an Argument

Once you have defined the function type, you can use it as a parameter type in another function:

func executeFunction(a int, b int, f MyFunctionType) int {
  return f(a, b)
}

Step 3: Use the Passed Function

Within the function body, you can invoke the passed function like any other.

package main

import "fmt"

// Define the function type
type MyFunctionType func(int, int) int

func executeFunction(a int, b int, f MyFunctionType) int {
  return f(a, b)
}

func main() {
  // Define a function that matches the MyFunctionType signature
  add := func(a int, b int) int {
  return a + b
 }

 // Pass the 'add' function to 'executeFunction'
 result := executeFunction(5, 3, add)
 fmt.Println(result) // Output: 8
}

Output

8

In this code, the executeFunction() function accepts a function of type MyFunctionType as an argument. We define an add function in the main function and pass it to executeFunction().

That’s it!