Go — Functions (Basics)

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, while 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:

The 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 the recursive function. Recursive functions are functions that continuously call themselves. This can end up in an infinite loop if you don't 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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikolaj Johannes Skole Jensen

Fullstack developer living in Denmark. Experience with both Web- and App development.