Skip to content
Codewilds

Lesson 11 of 38 · Functions

Go Multiple Return Values and Named Results

medium20 XP4 min read

Many languages let a function return just one value, so you end up packing several results into an array or an object. Go functions can return as many values as they need — and the whole language builds on one special case of this: returning a result and an error.

In this lesson you'll receive several results, skip the ones you don't need, meet Go's error convention and give your results names.

Returning several values

package main

import "fmt"

// minMax returns the smaller and the larger of a and b.
func minMax(a, b int) (int, int) {
	if a < b {
		return a, b
	}
	return b, a
}

func main() {
	lo, hi := minMax(8, 3)
	fmt.Println(lo, hi)
}
3 8

List the result types in parentheses, return the values separated by commas, and receive them with the same number of variables. When you assign the results, you must receive all of them: lo := minMax(8, 3) fails with assignment mismatch: 1 variable but minMax returns 2 values.

Go refuses to compile unused variables, so when you need only some results, assign the others to the blank identifier _, which simply throws a value away: _, hi := minMax(8, 3).

The (value, error) convention

A function that can fail returns its normal result plus an error as the last value. A nil error means success. On failure, the function returns zero values for the other results and an error describing the problem — errors.New creates one from a message:

package main

import (
	"errors"
	"fmt"
	"strconv"
)

// percent returns part as a percentage of total.
func percent(part, total int) (float64, error) {
	if total == 0 {
		return 0, errors.New("total must not be zero")
	}
	return float64(part) / float64(total) * 100, nil
}

func main() {
	p, err := percent(3, 4)
	fmt.Println(p, err)

	_, err = percent(1, 0)
	if err != nil {
		fmt.Println("error:", err)
	}

	n, err := strconv.Atoi("42x")
	fmt.Println(n, err)
}
75 <nil>
error: total must not be zero
0 strconv.Atoi: parsing "42x": invalid syntax

The caller checks if err != nil right after the call and deals with the problem before using the value. The standard library works the same way: strconv.Atoi converts text to an int and reports bad input with an error. Go doesn't use exceptions for this: errors are ordinary values that you return and check. A later chapter shows how to build richer errors.

Comma-ok: a bool instead of an error

When the only possible "failure" is not found, Go functions often return a bool instead of an error, usually named ok or found — the comma-ok pattern. strings.Cut splits a string around the first separator and reports whether it found one:

before, after, found := strings.Cut("key=value", "=")
fmt.Println(before, after, found)

before, after, found = strings.Cut("novalue", "=")
fmt.Printf("%q %q %v\n", before, after, found)
key value true
"novalue" "" false

You'll meet the same value, ok shape again when you look up keys in maps.

Named results and naked returns

Results can have names. They are declared as local variables that start at their zero values, and a bare return — a naked return — returns their current values:

// rectangle returns the area and the perimeter of a w × h rectangle.
func rectangle(w, h float64) (area, perimeter float64) {
	area = w * h
	perimeter = 2 * (w + h)
	return
}

func main() {
	fmt.Println(rectangle(3, 2))
}
6 10

Named results are good documentation: (area, perimeter float64) says much more than (float64, float64). Naked returns, however, hide what is returned. Keep them for short functions like this one and write return x, y, err explicitly everywhere else.

Common mistakes

  • Ignoring errors: n, _ := strconv.Atoi(input) silently turns bad input into 0. Discard an error only when it truly can't happen.
  • Using the value before checking the error: check err first, then use the result.
  • Putting the error first: (error, int) compiles, but every Go programmer expects the error last.
  • := with nothing new: x, err := ... fails with no new variables on left side of := when both variables already exist — for example as named results. Use =.

Assignment

Write three functions. Add errors, strconv and strings to the imports as you need them.

  1. DivMod(a, b int) (int, int) returns the quotient a / b and the remainder a % b. b is never zero.
  2. SplitName(full string) (first, last string) splits a name at its first space: "Ada Lovelace" gives "Ada" and "Lovelace", while "Mary Ann Smith" gives "Mary" and "Ann Smith". Without a space, the whole string is the first name and last is "".
  3. ParsePoint(s string) (x, y int, err error) parses a point written as "X,Y". Spaces around the numbers are allowed. If there is no comma, or either part is not a whole number, return 0, 0 and a non-nil error.
DivMod(17, 5)        // 3, 2
SplitName("Plato")   // "Plato", ""
ParsePoint("3,4")    // 3, 4, nil
ParsePoint("-2, 10") // -2, 10, nil
ParsePoint("34")     // 0, 0, error: no comma
ParsePoint("1,2,3")  // 0, 0, error: "2,3" is not a number

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Destructuring and multiple values in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 11 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.