Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - MULTIPLE RETURN


Go gives us an excellent feature with which we can return multiple values from a function.


Let us see in the below example.


Example :



package main
import "fmt"
    
func main() {
    
    first_num := 12
    second_num := 4   	
    add_val, mul_val, div_val := add_mul_div(first_num, second_num)
            
    fmt.Println("The Added result is :",add_val)	
    fmt.Println("The Multiplied result is :",mul_val)	
    fmt.Println("The Divided result is :",div_val)			 	
}
    
func add_mul_div(first_number int, second_number int) (int, int, int) {
    added_result := first_number + second_number
    multiplied_result := first_number * second_number
    divided_result := first_number/second_number
            
    return added_result, multiplied_result, divided_result 	
}


Output :



 The Added result is : 16
 The Multiplied result is : 48
 The Divided result is : 3

So, in the above example, we have a method, 'add_mul_div()' that performs the Addition,Multiplication and Division and returns three results.


Now, if you see the function definition,


func add_mul_div(first_number int, second_number int) (int, int, int) {

You can see that there are two parameters,


first_number int, second_number int

And since, we are going to return 3 values. We have mentioned the return types of all the three return values.


(int, int, int)

And in this case, we are going to return three integers. So, we have mentioned three 'int' return type.


Then in the function,


func add_mul_div(first_number int, second_number int) (int, int, int) {
    added_result := first_number + second_number
    multiplied_result := first_number * second_number
    divided_result := first_number/second_number
        
    return added_result, multiplied_result, divided_result 	
}

We have performed the addition and stored the added result in 'added_result' variable.


added_result := first_number + second_number

Performed the multiplication and stored the multiplied result in 'multiplied_result' variable.


multiplied_result := first_number * second_number

And performed the division and stored the divided result in 'divided_result' variable.


divided_result := first_number/second_number

Then we have returned all the three values, separated by comma.


return added_result, multiplied_result, divided_result

Using the return statement.


And while calling the function, we have taken the returned values in three variables.


add_val, mul_val, div_val := add_mul_div(first_num, second_num)

And displayed the result using the print statement.


fmt.Println("The Added result is :",add_val)	
fmt.Println("The Multiplied result is :",mul_val)	
fmt.Println("The Divided result is :",div_val)