- read

Go — Functions (Basics)

Nikolaj Johannes Skole Jensen 53


Functions are as important as in most programming languages. The first function you encounter when writing your first go project, is the “main” function:

You can specify the inputs and outputs of functions, here we have two inputs: x & y, both of type ints. We also specify the output type, also of type int:

Though we only specified one output type in the previous example you are able to return several values from a Go function:

In the previous examples we have two input parameters: x & y, whily we specified the type for each parameter explicitly there is a shorthand way to do it:


Another type of function in Go, is Variadic functions. Which are functions that will take an arbitrary number of ints as arguments:

Here we take an arbitrary number of numbers (“nums”) of type int, summing those up and returning that sum. Calling a variadic function, is just like calling other functions, you just have the possibility to have a dynamic amount of inputs to the function:


A third type of function in Go, is the anonymous function. Anonymous functions are quite useful when you want to define an inline function, in places where defining it with a name does not matter.

Here is an example of a function that returns another function: an anonymous function:


The fourth and last type of function that i will touch on in this article, is recursive functions. Recursive functions are functions that continously calls themselves. This can end up in an infinite loop, if you dont have a guard clause to cause the function to return. In the following example, this clause is defined by the if statement. A classic example to show recursion is calculating fibonacci numbers: