Go by Example

Multiple Return Values

Go functions can return more than one value - the canonical pattern is returning a result alongside an error.

Go functions can return multiple values. A common pair is (value, error): callers check the error before using the result.

List result types in parentheses and return nil when there is no error. Use _ to discard a value only when you do not need it.

package main
 
import (
    "errors"
    "fmt"
)
 
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
 
func main() {
    result, err := divide(10, 3)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Printf("%.2f\n", result)
}

In production

Named results can clarify a short function's contract. Bare return hides which values are returned, so use explicit return expressions once a function is long. The (value, error) pattern keeps failure handling visible at each call site.

Enjoyed this? Get more software craft delivered to your inbox.