Functions and multiple return values

Introduction

A function is a named piece of code that you can run again and again. Functions stop you from repeating yourself, they give names to ideas, and they let you test a small part of a program on its own. You have already used functions that other people wrote, such as fmt.Println. Go functions have two features that make them special: they can return more than one value, and they are values themselves, so you can pass a function to another function. This lesson covers both.

How it works

A function is declared with func, a name, the parameters with their types, and the type of the result:

func square(x int) int {
	return x * x
}

When two parameters have the same type, you can write the type once: func add(a, b int) int. A function with no result has no result type. You call a function with its name and values in brackets: square(7) gives 49.

A Go function may return several values. List their types in brackets, and receive them on the left side of :=:

func divmod(a, b int) (int, int) {
	return a / b, a % b
}

q, r := divmod(17, 5)

This is how Go functions report errors: the second value is often an error, as you saw with strconv.Atoi. If you do not need one of the values, write _ instead of a name. Results can also be named, as in (min, max int); then a plain return sends back their current values.

A variadic function takes any number of values of one type. The parameter is written nums ...int, and inside the function it behaves like a list of ints.

Functions are values. You can keep one in a variable, pass it as a parameter and return it. A function made inside another function is a closure: it keeps the variables it uses. A function that returns a counter function is the standard small example. A function can also call itself, which is recursion. A recursive function needs a base case that stops it, otherwise it never ends.

The keyword defer puts a call on hold until the surrounding function ends, even when it ends early. It is often used for clean-up work. Deferred calls run in reverse order, last in first out.

Parameters are copied: a function that changes its parameter changes only its own copy. Lesson 11 shows how pointers let a function change the original.

Example

package main

import "fmt"

func square(x int) int {
	return x * x
}

func divmod(a, b int) (int, int) {
	return a / b, a % b
}

func minMax(nums ...int) (min, max int) {
	min, max = nums[0], nums[0]
	for _, v := range nums {
		if v < min {
			min = v
		}
		if v > max {
			max = v
		}
	}
	return
}

func fact(n int) int64 {
	if n <= 1 {
		return 1
	}
	return int64(n) * fact(n-1)
}

func apply(f func(int) int, x int) int {
	return f(x)
}

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func main() {
	defer fmt.Println("main is done")
	fmt.Println(square(7))
	q, r := divmod(17, 5)
	fmt.Println(q, r)
	lo, hi := minMax(4, 9, -2, 7)
	fmt.Println(lo, hi)
	fmt.Println(fact(20))
	fmt.Println(apply(square, 12))
	next := counter()
	next()
	next()
	fmt.Println(next())
}

Line by line

  1. square takes an int and returns an int. divmod returns two ints.
  2. minMax(nums ...int) accepts any number of ints and has the named results min and max; the plain return sends them back.
  3. fact calls itself with n - 1 and stops at the base case. It returns an int64, so it can hold 20!.
  4. apply takes a function as a parameter, and counter returns a function that remembers count.
  5. defer runs its Println when main ends, after all other output.

Expected result

49
3 2
-2 9
2432902008176640000
144
3
main is done

In the real world

Real programs are built from hundreds of small functions. A good function does one thing and has a name that says what it does. The standard library is full of functions that return a value and an error, and Go programmers get used to the pattern result, err := doSomething(). Closures are used for callbacks and for things like sorting rules.

Common mistakes

  • Forgetting to return a value in a function that has a result type.
  • Ignoring a returned value by mistake. Go makes you take or discard every value with _.
  • Recursion without a base case, which runs until the program stops.
  • Expecting a function to change its parameter for the caller. It changes only a copy.
  • Writing a function that does too much instead of splitting it.

Best practices

  • Give functions short, clear names, and keep each to one job.
  • Return an error as the last value when something can go wrong.
  • Use named results only in short functions, where they make the code clearer.

Summary

Functions are declared with func, typed parameters and result types. Go functions can return several values, take a variable number of arguments with ..., and be stored, passed and returned like any value. Recursion needs a base case, a closure remembers the variables around it, and defer runs a call when the function ends.

Quick check

1. How do you receive two results from divmod(17, 5)?
2. What does nums ...int mean in a parameter list?
3. What does a recursive function need to avoid running forever?
4. When does a deferred call run?
5. What is a closure?

Key takeaways

  • A function lists its parameter types and result types: func add(a, b int) int.
  • A function can return several values; the caller takes them with a, b := f().
  • Functions are values: you can store them in variables, pass them and return them.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.