0
0
Goprogramming~5 mins

Multiple return values in Go

Choose your learning style9 modes available
Introduction
Sometimes a function needs to give back more than one piece of information. Multiple return values let a function send back several results at once.
When you want to return a result and an error from a function.
When you want to return two related values, like a quotient and remainder from division.
When you want to return a status and a message from a function.
When you want to return coordinates like x and y from a function.
Syntax
Go
func functionName() (type1, type2) {
    // code
    return value1, value2
}
You list the types of all return values inside parentheses.
Use commas to separate multiple return values in the return statement.
Examples
Returns quotient and remainder of dividing a by b.
Go
func divide(a, b int) (int, int) {
    return a / b, a % b
}
Returns first and last name as two strings.
Go
func getName() (string, string) {
    return "John", "Doe"
}
Returns a boolean status and a message.
Go
func status() (bool, string) {
    return true, "Success"
}
Sample Program
This program divides 10 by 3 and prints the quotient and remainder returned by the divide function.
Go
package main
import "fmt"

func divide(a, b int) (int, int) {
    return a / b, a % b
}

func main() {
    quotient, remainder := divide(10, 3)
    fmt.Printf("Quotient: %d, Remainder: %d\n", quotient, remainder)
}
OutputSuccess
Important Notes
You can ignore some return values by using the blank identifier _ if you don't need them.
Multiple return values are very common in Go for returning results and errors together.
Summary
Functions can return more than one value by listing types in parentheses.
Use commas to return multiple values together.
This helps send back extra information like errors or multiple results.