Learn Go← Dashboard

Parameters, multiple returns, variadic, closures, and defer.

Multiple Return Values

Go functions can return more than one value. This is how Go does error handling: the function returns whatever it produces, plus an error. The caller checks the error and decides what to do.

The (value, error) pattern

go playground
Loading...

You'll see this pattern everywhere in Go. The convention is:

  1. The "success" value comes first.
  2. The error comes last.
  3. If err != nil, ignore the other return values — they may be zero/garbage.

Named return values

You can name your return values. They behave like local variables initialized to their zero value, and a bare return returns them.

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return    // returns x, y implicitly
}

Returning more than two values

func parseAddr(s string) (proto string, host string, port int, err error) { ... }

Three or four is fine. If you keep adding, that's a hint you should be returning a struct instead.

Discarding returns with _

You must assign every return value, but _ discards one:

n, _ := strconv.Atoi(s)   // I trust this is a number
_ = doThing()             // explicitly ignore the error (almost always a code smell)
`n, err := strconv.Atoi("oops")` returns an error. What’s the safe assumption about `n`?