Golang Program that Uses Multiple Return Values

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



filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


Output : 
 

Max =  70 
Min =  50

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

 

GO

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


Output : 
 

Sum =  168 
Difference =  -32



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.