Hello everyone, In this tutorial, we will show you how to return multiple values in the Go language. The following example program has been tested and shared in the post.

Syntax

func function_name(arg1 type, arg2 type, ...) (return_type1, return_type2, ...) {
return return_value1, return_value2, ...
}

Go – Return and Get Multiple Values from Function

The Go programming language has many notable features, returning a multiple-values from the function is one of the cool features with Go programming language. In the below example, we have created a function called arithmetic() which is responsible to perform arithmetic operations such as Addition, Subtraction, Multiplication, and Division by taking two integer numbers as argument. The arithmetic() function execute and will return multiple outputs for each operation.

package main
import (
"fmt"
)
func main() {
var a, b int
fmt.Println("Enter the first number : ")
fmt.Scanf("%d", &a) // reading first number
fmt.Println("Enter the second number : ")
fmt.Scanf("%d", &b) // reading second number
// assigning the multiple returned values to variables
var add, sub, mul, div int = arithmetic(a, b)
fmt.Println("the given a = ", a, "and b = ", b)
fmt.Println("Addition :", add)
fmt.Println("Subtraction :", sub)
fmt.Println("Multiplication :", mul)
fmt.Println("Division :", div)
}
func arithmetic(a int, b int) (int, int, int, int) {
return a + b, a - b, a * b, a / b
}

Output

Enter the first number : 
20
Enter the second number : 
10
the given a =  20 and b =  10
Addition : 30
Subtraction : 10
Multiplication : 200
Division : 2

References

  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println
  5. https://golang.org/pkg/fmt/#Scanf

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *