intermediate18 min

Functions and Multiple Return Values

Declaring functions, and Go's distinctive support for returning more than one value.

What you'll learn

  • Declare a function with typed parameters and a return type
  • Return and receive multiple values from a single function call
  • Explain why Go's error-handling idiom depends on multiple return values

Explanation

A Go function declares its parameter types and return type explicitly: func add(a int, b int) int { return a + b }. Consecutive parameters sharing a type can drop the repeated type name: func add(a, b int) int.

Go functions can return more than one value -- a feature many other mainstream languages don't have built in. This is written as func divide(a, b int) (int, int) { return a / b, a % b }, and callers receive both values: quotient, remainder := divide(17, 5).

This isn't just a convenience -- it's the foundation of Go's core error-handling idiom, which you'll see properly in a later lesson: a function that might fail returns its normal result and an error value, e.g. func parse(s string) (int, error), and the caller checks the error before trusting the result.

If you don't need one of the returned values, you can discard it with the blank identifier _, e.g. quotient, _ := divide(17, 5) if you only care about the quotient.

Guided lab

Predict: A function with two return values

GoNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, predict what it does, then reveal the real expected output.

Read this program and predict exactly what it prints.

package main

import "fmt"

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

func main() {
	q, r := divide(17, 5)
	fmt.Printf("17 / 5 = %d remainder %d\n", q, r)
}

Stuck? Get a hint.

Common mistakes

  • Forgetting to receive all values a multi-return function produces -- Go requires you to either use or explicitly discard (`_`) every returned value at the call site.
  • Mismatching the number of variables on the left of `:=` with the number of values a function actually returns.
  • Assuming multiple return values are a special struct or tuple type -- they aren't; they're just multiple plain values in the function signature.

Knowledge check

Knowledge check

1. What is the blank identifier `_` used for with a multi-return function?
2. What Go idiom does multiple return values make possible?
3. Given `func add(a, b int) int`, what does the shared `int` before the parameter list mean?

Takeaway

Go functions can return multiple values directly, which is the foundation of its `(result, error)` error-handling idiom.

Summary

Functions declare typed parameters and return types; Go's multi-value returns let a function hand back more than one result, discardable with `_`.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.

Next: Arrays and Slices