Golang Program that Uses Multiple Return Values
Last Updated :
23 Aug, 2021
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"
func maxmin(a int, b int) (int, int) {
if a > b {
return a, b
} else {
return b, a
}
}
func main() {
var a = 50
var b = 70
var max, min = maxmin(a, b)
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"
func sumDiff(a int, b int) (int, int) {
return (a + b), (a - b)
}
func main() {
var a = 68
var b = 100
var sum, diff = sumDiff(a, b)
fmt.Println( "Sum = " , sum, "\nDifference = " , diff)
}
|
Output :
Sum = 168
Difference = -32
Share your thoughts in the comments
Please Login to comment...