Functions as Parameters in Go

F
We'd bet you anything that any programming language capable of shipping production level code supports functions.

When it comes to Go, functions are first-class citizens which means you can treat them like any other value like an integer, string or struct.

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

In this tutorial, we will introduce you to this programming paradigm that establishes a good foundation for clean and modular code.

Functions in Go: Basics

Before we pass functions as parameters, let's explore the basic syntax of Go functions:

func functionName,parameters, return_type ,
//function body
,
return return value
,

A function in Go consists of the following components:

  • func – The keyword that is used to declare a function.
  • functionName – Name of the function.
  • Parameters – Input parameters enclosed in parentheses, if any.
  • return_type – The data type that the function returns, if any.
  • Return – Keyword which is used to return a value from the function to which it is applied.

function type

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

Consider the following example tasks:

add func,A, b int here, int here ,

return A + B
,

subtract function,A, b int here, int here ,
return a – b
,

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

Note: The function type is essential when passing a function as a parameter as it ensures that we are passing the correct type of function.

Passing a function as a parameter

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

An example is as follows:

funk fn,A, b int here, operation funk,int here, int here, int here, int here ,
Result :, Operation,A, b,
return Result
,

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

  1. A and B – They represent integer values ​​for the operands.
  2. Operand – It is a function of type func(int, int) int that performs the desired operation.

We can then call the function and provide it with the action we want it to provide.

Add result:, F.N,5, 3, Add,

conclusion

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

Add comment

By Ranjan