Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 147 ยท Functions

Multiple Return Values and Named Results

Learn how Go functions return several values, the (value, error) convention, named results, naked returns and why they are risky, and how to ignore values with the blank identifier.

Most languages let a function return one thing. If you need two, you pack them into a tuple, an object or an out-parameter. Go takes a simpler route: a function can return any number of values, and the caller receives them directly. This one feature shapes a huge part of everyday Go, because it is how functions report both a result and whether the result can be trusted.

In this lesson you'll write functions with several results, learn the (value, error) convention you will see in nearly every Go package, and meet named results: result variables with names, which document your function and interact with defer in a very useful way. You'll also see why the shortcut called a naked return is often a bad idea.

Returning more than one value

List the result types in parentheses after the parameter list. A return statement then supplies one value for each type, and the caller assigns them with a multiple assignment:

Go A function with two results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last line shows a handy rule: if a call returns several values, f(g()) passes all of them to f as separate arguments, as long as g's results match f's parameters exactly. That is why fmt.Println(divmod(100, 7)) prints both numbers. The rule only works when the call is the only argument; you can't write fmt.Println("x", divmod(1, 2)).

You must use every result of a call, or discard it explicitly. Go refuses to compile code that assigns only some of them:

Go Receiving the wrong number of values (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with ./main.go:10:7: assignment mismatch: 1 variable but divmod returns 2 values. The error points at the exact column of the :=. Go insists on this strictness so a result never disappears silently.

The (value, error) convention

Go has no exceptions for ordinary failures. Instead, a function that can fail returns its result and an error as the last value. If the error is nil, everything worked and the other value is meaningful. If it is not nil, something went wrong and you should not trust the other value.

Go Returning a result and an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice the pattern in main: call, check err, and return early on failure so the happy path stays at the left margin. You will write if err != nil thousands of times. Errors as Values explains why Go made this choice and how to build richer errors, and Error Handling Patterns shows how to keep it tidy.

When a function fails, the other results are conventionally the zero value of their type (here 0). Callers should not rely on those zeros, but returning zeros is polite and avoids surprises.

The error is always the last result, and its static type is the interface error. Standard library functions follow this without exception, for example strconv.Atoi(s) returns (int, error) and os.ReadFile(name) returns ([]byte, error).

The comma-ok idiom

Besides errors, multiple results show up in the comma-ok idiom. Some operations return a second bool that tells you whether the first value is real. You'll meet it with maps, type assertions and channels, and it is also easy to write yourself:

Go Writing a function in the comma-ok style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Use a bool when "not found" is a normal outcome, and an error when you want to explain why something failed. The if v, ok := f(); ok { ... } form keeps v and ok scoped to the if, as described in if, else if and else.

Ignoring results with the blank identifier

Sometimes you only want one of the results. Assign the others to the blank identifier _, which discards a value without creating a variable, so the "declared and not used" rule doesn't apply:

Go Discarding a result with underscore

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first two uses are fine. The last one is a trap: strconv.Atoi failed, but the program carries on with n == 0 and nobody knows. Ignore an error only when you are certain it cannot matter, and ideally leave a comment saying why.

Named results

You can give the results names in the signature. Each name becomes a local variable, initialized to its zero value, that is in scope for the whole function:

Go Named results document the meaning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The names are mainly documentation. With (float64, float64) a reader can't tell which number is which, but (area, perimeter float64) says it in the signature, and editors and go doc show it. Names are most helpful when several results have the same type.

Naked returns

When a function has named results, a bare return with no values returns the current value of those variables. This is called a naked return:

Go A naked return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

That is legal and works. But in anything longer than a few lines, naked returns hurt readability: the reader must scroll up to see what is being returned. The common advice, and the style used by the standard library for long functions, is use naked returns only in very short functions, and always write the values explicitly otherwise.

There is also a scoping trap. If an inner block declares a variable with the same name as a result, a naked return is a compile error:

Go Shadowed result and naked return (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:12:4: result parameter n not in scope at return (and the same for err), with a note such as inner declaration of var n int pointing at line 10. The := inside the if created new variables n and err that hide the results. Writing return n, err explicitly avoids the whole class of bug.

Named results and defer

Named results have one genuinely powerful use: a deferred function runs after the return statement has set the result variables, so it can read or change them. This is the standard way to add context to an error or recover from a panic:

Go A deferred function changes a named result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The deferred closure sees the final err and wraps it. Without a named result there would be no variable for the closure to modify. defer covers this technique in detail, and Wrapping and Inspecting Errors explains %w.

Design advice

  • Return two or three values at most. If you need more, return a struct.
  • Put the error last, and the "ok" bool last when there is no error.
  • Prefer returning (T, error) over a magic value such as -1. A caller cannot forget to look at an error that the compiler forces them to receive.
  • Use named results for documentation and for defer, not as a way to skip writing return values.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you compile x := divmod(17, 5) if divmod returns two ints?

    Go requires you to receive every result or discard it with the blank identifier. Assigning two results to one variable is the error 'assignment mismatch: 1 variable but divmod returns 2 values'.
  2. 2. Where does Go convention put the error in a result list?

    The error is the last result, as in (int, error) or ([]byte, error). Callers can then always write value, err := f().
  3. 3. Given func f() (a, b int) { a = 1; b = 2; return }, what does x, y := f() assign?

    A naked return returns the current values of the named results, so x is 1 and y is 2. It is legal, just easy to misread in longer functions.
  4. 4. Why can a deferred function modify the value a function returns?

    A return statement stores its values in the result variables, then deferred calls run, then the function returns. If the results are named, a closure can read and change them in between.
  5. 5. What does _, ok := m[key] do?

    The blank identifier discards the value, and ok tells you whether the key was present.

Summary

  • A function can return several values: func f() (int, string). The caller must receive all of them or use _.
  • f(g()) passes all of g's results to f when the call is the only argument.
  • By convention a function that can fail returns (result, error) with the error last; check err != nil right away and return early.
  • The comma-ok idiom uses a bool for "was it found?" and is used by maps, type assertions and channel receives.
  • Named results are zero-initialized local variables that document the signature and let deferred functions change what is returned.
  • Naked returns are legal but hurt readability beyond very short functions; shadowing a result inside a block makes them a compile error.

Next: Variadic Functions shows how a function can accept any number of arguments.