Go gives us an excellent feature with which we can return multiple values from a function.
Let us see in the below 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 }
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,
You can see that there are two parameters,
And since, we are going to return 3 values. We have mentioned the return types of all the three return values.
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.
Performed the multiplication and stored the multiplied result in 'multiplied_result' variable.
And performed the division and stored the divided result in 'divided_result' variable.
Then we have returned all the three values, separated by comma.
Using the return statement.
And while calling the function, we have taken the returned values in three variables.
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)