0
0
GoHow-ToBeginner · 3 min read

How to Return Multiple Values from Function in Go

In Go, you can return multiple values from a function by listing the return types in parentheses after the function signature and returning the values separated by commas using the return statement. This allows functions to send back more than one result directly.
📐

Syntax

To return multiple values from a function in Go, specify the return types inside parentheses after the function name. Use the return statement followed by the values separated by commas.

  • func: keyword to declare a function
  • functionName: name of the function
  • (parameters): input parameters (optional)
  • (type1, type2, ...): multiple return types inside parentheses
  • return value1, value2, ...: return multiple values separated by commas
go
func functionName() (type1, type2) {
    // function body
    return value1, value2
}
💻

Example

This example shows a function that returns two values: an integer and a string. It demonstrates how to declare multiple return types and how to receive them when calling the function.

go
package main

import "fmt"

func getUser() (int, string) {
    id := 101
    name := "Alice"
    return id, name
}

func main() {
    userID, userName := getUser()
    fmt.Println("User ID:", userID)
    fmt.Println("User Name:", userName)
}
Output
User ID: 101 User Name: Alice
⚠️

Common Pitfalls

Common mistakes when returning multiple values in Go include:

  • Not enclosing multiple return types in parentheses.
  • Returning a different number of values than declared.
  • Ignoring one or more returned values without using the blank identifier _.

Always ensure the number and types of returned values match the function signature.

go
package main

import "fmt"

// Wrong: missing parentheses around return types
// func wrongReturn() int, string {
//     return 1, "error"
// }

// Correct:
func correctReturn() (int, string) {
    return 1, "success"
}

func main() {
    a, b := correctReturn()
    _ = a // ignoring a value properly
    fmt.Println(b)
}
Output
success
📊

Quick Reference

Remember these tips when working with multiple return values in Go:

  • Use parentheses to group multiple return types.
  • Return values in the same order as declared.
  • Use the blank identifier _ to ignore unwanted return values.
  • Multiple return values are useful for returning results and errors together.

Key Takeaways

Declare multiple return types inside parentheses after the function signature.
Return multiple values separated by commas matching the declared types and order.
Use the blank identifier _ to ignore unwanted returned values.
Always ensure the number of returned values matches the function signature.
Multiple return values are a simple way to return results and errors together.