Open In App

Golang Program that Uses Multiple Return Values

Last Updated : 23 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In Golang, we can return multiple values at a time from a single function. Multiple return values can be achieved by changing the return type of the function in the function signature.

Syntax : 

func value( ) ( int , int ) { 
return 1 , 0 ; 
} 

The (int, int) in this function signature explains that the return type is two integers. Thus we have to use multiple assignments while calling this function. This feature is also used to return both results and error from a function. If you want a subset of the returned values, use the blank identifier _.

Example 1: Finding max and min of two elements, using this feature : 

Go




package main
 
import "fmt"
 
// declaring a function
// having return type
// of int, int
func maxmin(a int, b int) (int, int) {
 
    if a > b {
     
        // separate multiple return
        // values using comma
        return a, b
    } else {
 
        return b, a
    }
    // this function returns
    // maximum , minimum values
}
 
func main() {
 
    // declaring two values a and b
    var a = 50
    var b = 70
 
    // calling the function
    // with multiple assignments
    var max, min = maxmin(a, b)
 
    // Printing the values
    fmt.Println("Max = ", max, "\nMin = ", min)
}


Output : 

Max =  70 
Min =  50

Example 2: Finding the sum and difference of two numbers, using this feature of multiple return values.

Go




package main
 
import "fmt"
 
// declaring a function having
// return type of int, int
func sumDiff(a int, b int) (int, int) {
 
    return (a + b), (a - b)
 
    // this function returns sum ,
    // difference of the two numbers
}
 
func main() {
 
    // declaring two values a and b
    var a = 68
    var b = 100
 
    // calling the function
    // with multiple assignments
    var sum, diff = sumDiff(a, b)
 
    // Printing the values
    fmt.Println("Sum = ", sum, "\nDifference = ", diff)
}


Output : 

Sum =  168 
Difference =  -32


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads