golang

Functions as Parameters in Go (Function as Parameter)

We can bet you anything that any programming language that is capable of shipping the production-level code supports functions.

When it comes to Go, functions are first-class citizens which means that you can treat them like any other value such as integers, strings, or structs.

This makes them very powerful as they can basically pass the functions as parameters to other functions which is a very good recipe for building a flexible and efficient code.

In this tutorial, we will introduce you to this programming paradigm which sets up a good foundation for good and modular code.

Functions in Go: The Basics

Before we delve into passing the functions as parameters, let us explore the basic syntax of a Go function:

func functionName(parameters) return_type {
    // Function body
    // ...
    return returnValue
}

A function in Go is comprised of the following components:

  • func – The keyword that is used to declare a function.
  • functionName – The name of the function.
  • parameters – The input parameters enclosed in parentheses, if any.
  • return_type – The data type that the function returns, if any.
  • return – The keyword that is used to return a value from the function where it is applicable.

Function Types

In Go, functions have types just like any other data type. The type of a function is determined by its parameter types and return type.

Consider the following example functions:

func add(a, b int) int {
    return a + b
}

func subtract(a, b int) int {
    return a - b
}

In the given example functions, the “add” and “subtract” functions have a type of int as they return an “int” type.

NOTE: Function type is essential when passing the functions as parameters because it ensures that we are passing the correct type of function.

Passing the Functions as Parameters

To pass a function as a parameter to another function, we simply include the function type as the parameters type.

An example is as follows:

func fn(a, b int, operation func(int, int) int) int {
    result := operation(a, b)
    return result
}

In this example, the “fn” function accepts three parameters:

  1. a and b – They represent the integer values for the operands.
  2. Operand – This is a function of type func(int, int) int which carries out the desired operation.

We can then call the function and provide it with the task that we wish it to provide.

resultAdd := fn(5, 3, add)

Conclusion

In this guide, we covered the fundamentals of working with functions as parameters in Go.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list