How to Pass Function as Parameter in Golang

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.

Example

package main

import (
  "fmt"
)

 // Define a function type called "operation"
 type operation func(int, int) int

 // Add is a simple function that adds two integers
 func Add(x, y int) int {
   return x + y
 }

 func Subtract(x, y int) int {
   return x - y
 }

 func PerformOperation(f operation, x, y int) int {
   return f(x, y)
 }

 func main() {
  a, b := 21, 19

  // Pass the Add function as a parameter to PerformOperation
  result := PerformOperation(Add, a, b)
  fmt.Printf("%d + %d = %d\n", a, b, result)

  // Pass the Subtract function as a parameter to PerformOperation
  result = PerformOperation(Subtract, a, b)
  fmt.Printf("%d - %d = %d\n", a, b, result)
}

Output

21 + 19 = 40
21 - 19 = 2

In this example, we defined a function type called operation that takes two integers as input and returns an integer. In addition, we defined two functions, Add() and Subtract(), that match the operation function signature.

The PerformOperation() function takes a function of type operation and two integers as parameters.

Inside the PerformOperation() function, we called the passed function f with the given integers and returned the result.

In the main() function, we called PerformOperation() with the Add() and Subtract() functions as parameters and printed the results.

That’s it.

Leave a Comment