Introduction to Functions

This lesson discusses the introductory concepts of functions in Go before going into detail.

Functions are the basic building blocks of the Go code. They are very versatile, so Go can be said to have a lot of characteristics of a functional language. Functions are a kind of data because they are themselves values and have types. Let’s start this chapter by elaborating on the elementary function-description, which we discussed briefly in Chapter 2.

Basics of a function in Go

Every program consists of several functions. It is the basic code block. The order in which the functions are written in the program does not matter. However, for readability, it is better to start with main() and write the functions in a logical order (for example, the calling order).

Purpose of a function

The main purpose of functions is to break a large problem, which requires breaking many code lines into a number of smaller tasks. Also, the same task can be invoked several times, so a function promotes code reuse. In fact, a good program honors the Don’t Repeat Yourself principle, meaning that the code which performs a certain task may only appear once in the program.

Execution of a function

A function ends when it has executed its last statement before }, or when it executes a return statement, which can be with or without argument(s). These arguments are the values that a function returns from their computation. There are 3 types of functions in Go:

  • Normal functions with an identifier
  • Anonymous or lambda functions
  • Methods

Any of these can have parameters and return values.

The definition of all the function parameters and return values together with their types is called the function signature. As a reminder, a syntax prerequisite like:

func g()

{ // INVALID
 ...
}

is invalid Go-code. It must be:

func g() { // VALID
 ...
}

A function is called or invoked in code in a general format like:

pack1.Function(arg1,arg2,...,argn)

Function is a function in package pack1, and arg1, and so on are the arguments. When a function is invoked, copies of the arguments are made, and these are then passed to the called function.

The invocation happens in the code of another function called the calling function. A function can call other functions as much as needed, and these functions, in turn, can call other functions. This can go on with theoretically no limit (unless the stack upon which these function calls are placed is exhausted).

Here is the simplest example of a function calling another function without needing arguments:

Get hands-on with 1200+ tech skills courses.