Skip to main content
Go has built-in support for multiple return values, a feature that distinguishes it from many other languages. This capability is extensively used in idiomatic Go, particularly for returning both result and error values from functions.

Basic Syntax

To return multiple values, specify the return types in parentheses in the function signature:
func vals() (int, int) {
    return 3, 7
}
The (int, int) in the signature indicates that this function returns two int values.

Receiving Multiple Return Values

Use multiple assignment to receive all return values:
a, b := vals()
fmt.Println(a)  // Output: 3
fmt.Println(b)  // Output: 7

The Blank Identifier

If you only need a subset of the returned values, use the blank identifier _ to ignore unwanted values:
_, c := vals()
fmt.Println(c)  // Output: 7
The blank identifier _ is a write-only variable that allows you to discard values you don’t need. This is particularly useful when a function returns an error you want to ignore (though this is generally not recommended in production code).

Complete Example

package main

import "fmt"

// Function returning two integers
func vals() (int, int) {
    return 3, 7
}

func main() {
    // Receive both return values
    a, b := vals()
    fmt.Println(a)
    fmt.Println(b)

    // Use blank identifier to ignore first value
    _, c := vals()
    fmt.Println(c)
}

Common Use Cases

Error Handling

The most common pattern: returning a result and an error
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

Boolean Checks

Returning a value and a boolean indicating success
func getUserByID(id int) (User, bool) {
    user, exists := userMap[id]
    return user, exists
}

Named Return Values

Go also supports named return values, which can make code more readable:
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return  // naked return
}
While named returns can improve readability for short functions, naked returns (returns without arguments) can reduce clarity in longer functions. Use them judiciously.

Best Practices

When a function returns an error as one of multiple values, always check it:
result, err := someFunction()
if err != nil {
    // Handle error
}
By convention, error values are returned as the last return value:
func readFile(path string) ([]byte, error) {
    // Not: (error, []byte)
}
While Go supports many return values, keeping them to 2-3 improves readability. Consider using a struct for more complex returns.

Key Takeaways

  • Go natively supports returning multiple values from functions
  • Use multiple assignment to receive all return values
  • The blank identifier _ lets you ignore unwanted values
  • Multiple returns are commonly used for error handling patterns
  • By convention, errors are returned as the last value

Build docs developers (and LLMs) love