Golang Basics - Functions

If you're building a program that's more complex than a couple of for loops, you'll need to use functions. Functions in Go are defined using the func keyword. Let's look at an example of a function in Go thats adds two numbers:

//1   2   3             4
func add(a int, b int) int {
// 5: function body
        sum := a + b

//      6
        return sum

// A function is called by providing the arguments
result := add(3, 5)

// 8

We can deconstruct this function into multiple parts:

  1. func - keyword used to declare the function
  2. add - the function name. Just like variables, the case of the first letter determines the public or private scope of the function. The add function cannot be accessed outside its package, but the Add function can.
  3. a int, b int - the arguments. The type of each argument needs to be specified. In this case, both a and b are integers
  4. int - the return value
  5. The function body, which contains the code that the function should execute. All variables declared within the function body, as well as the arguments, are scoped to the function itself. This means a, b and sum cannot be accessed outside the function.
  6. The return statement. Every function has to have a return statement (unless the function has no return value), otherwise the code won't compile.

In case all your arguments are of the same type, like in the add function, we can mention the type at the end like so:

func add(a, b int) int {

Multiple return values

A function can return multiple values. For this, each return value needs to be separated by a comma:

func divide(a, b int) (int, int) {
        quotient := a/b
        remainder := a%b
        return quotient, remainder

q, r := divide(8, 3)
fmt.Println(q, r)
// 2, 2

Named return values

You can also name your return values while declaring the function:

// In this case, the quotient and remainder variables are declared along with the function
// The are initialized with the default zero value of the type (in this case 0)
func divide(a, b int) (quotient int,remainder int) {
        // Note that we are using `=` instead of `:=`
        // because the variables have already been declared
        quotient = a/b
        remainder = a%b
        // The return statment doesn't contain the values to return
        // `quotient` and `remainder` are returned by default

q, r := divide(8, 3)
fmt.Println(q, r)
// 2, 2

Functions without arguments or return values

It is possible for a function to have no arguments, no return values or both. For example, the main function does not have arguments and does not return anything:

func main() {

// A function without a return value
func addAndPrint(a, b int) {
        fmt.Println(a + b)

// A function without arguments
var counter int
func getCount() int {
        return counter

📖 Read next: Methods

Liked this article? Share it on: