Skip to content
Related Articles

Related Articles

Golang Program that Uses Multiple Return Values
  • Last Updated : 17 Aug, 2020

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 intergers. 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 numebrs
}
  
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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :