Go Multiple Return Values

Go functions can return more than one value at the same time. This is a distinctive feature of Go that makes error handling and data extraction clean and straightforward, without needing special wrapper objects.

Returning Two Values

package main

import "fmt"

func minMax(a, b int) (int, int) {
    if a < b {
        return a, b
    }
    return b, a
}

func main() {
    min, max := minMax(10, 30)
    fmt.Println("Min:", min) // Min: 10
    fmt.Println("Max:", max) // Max: 30
}

The Most Common Use – Returning a Value and an Error

Go's standard pattern for functions that can fail is to return the result along with an error. If the error is nil, the operation succeeded.

package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero is not allowed")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result) // Result: 5
    }

    result2, err2 := divide(10, 0)
    if err2 != nil {
        fmt.Println("Error:", err2) // Error: division by zero is not allowed
    } else {
        fmt.Println("Result:", result2)
    }
}

Return Pattern Diagram

func divide(a, b float64) (float64, error)
                              │        │
                              │        └── second return: error or nil
                              └─────────── first return: computed result

Caller receives both:
result, err := divide(10, 2)
  │               │
  │               └── if err != nil, something went wrong
  └────────────────── only use result when err is nil

Ignoring One Return Value

Use the blank identifier _ to discard a return value that is not needed.

package main

import "fmt"

func getNameAndAge() (string, int) {
    return "Alice", 30
}

func main() {
    name, _ := getNameAndAge() // ignore age
    fmt.Println(name)          // Alice
}

Returning Three or More Values

package main

import "fmt"

func studentInfo() (string, int, float64) {
    return "Bob", 20, 89.5
}

func main() {
    name, age, gpa := studentInfo()
    fmt.Printf("Name: %s, Age: %d, GPA: %.1f\n", name, age, gpa)
}

Output:

Name: Bob, Age: 20, GPA: 89.5

Key Points

  • Go functions return multiple values by listing types inside parentheses
  • The standard Go pattern returns a result and an error together
  • Always check the error before using the result
  • Use _ to discard return values that are not needed
  • This feature replaces the need for wrapper objects or exceptions

Leave a Comment