Table of contents
1.
Introduction
2.
Definition
3.
Declaration
3.1.
Same Return Types
3.2.
Different Return Types
4.
Example
4.1.
Code
4.2.
Output
5.
Features and Uses
6.
Frequently Asked Questions
6.1.
What is the need for skipping return values?
6.2.
Can a function return multiple values?
6.3.
In Golang, what does panic() do?
6.4.
In Golang, what is defer?
7.
Conclusion
Last Updated: Mar 27, 2024

Go Functions Returning Multiple Values

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Functions in Go, like JavaScript, are first-class citizens. Basically, "being able to do what everyone else can do" is what first-class citizenship implies. Functions can be assigned to variables, passed as arguments, invoked immediately, or deferred until the end. Functions and methods in Go can return multiple values, which is a unique feature.

We will discuss this unique feature of returning multiple values by Go functions with examples and use cases. So without any further ado, let’s start!

Definition

Any number of return values is possible for a function. Internally, Go supports this. A single return statement can return several values. The return values are of the same type as the parameters in the parameter list.

Let's have a look at how a function can return multiple results. The multi-return function's syntax is as follows:

func function_name(p1 paraType 1, p2 paraType 2, p3 paraType3,......)(returnType 1, returnType 2, returnType 3,.....){
     //  some code...
}

Return Type is optional and contains the types of values returned by the function. If We're going to use return type in our function, we'll need to include a return statement in our function.

Declaration

As we will see, return types and values can be specified in various ways. We can declare it in the following manner when returning multiple kinds of values.

package main
import (
    "fmt"
)
func doubleInt(x int) (int) {
    return x * 2
}
func main() {
    fmt.Println(doubleIt(6))  // prints 12
}

Same Return Types

If we have return values of the same type, we can declare it like this to make our code shorter.

package main 
import (
    "fmt"
)
func sameReturnType(a int) (int, int) {
    return a/2, a*2
}
func main() {
    x, y := sameReturnType(18)     
   fmt.Println(x, y)  // 9 36
}

Different Return Types

If we want to use several types of return values, we may express it like this.

package main
import (
    "fmt"
)
func difReturnType(a int) (int, float64) {
    return a/2, float64(a)*2.05
}
func main() {
    x, y := difReturnType(6)
     
    fmt.Println(x, y)  // 3 12.29999999999999
}

Example

Here is an example of a Go function returning multiple values.

  • This function's signature indicates that it returns two ints (int, int).
  • The two different return values from the call with multiple assignments are used here.
  • Use the blank identifier(_) if you require a subset of the returned values.

Code

package main
import "fmt"
//function returns two int values
func example() (int, int) {
return 3, 1
}
func main() {
x, y := example()
fmt.Println(x)
fmt.Println(y)
// use the blank identifier `_` for a subset of return values.
_, c := example()
fmt.Println(c)
}

Output

Features and Uses

Multiple return values are beneficial when verifying errors. Because we are demonstrating the errors one by one, making the program flow easier. Thus, elaborate and nested error-checking and other issues are not required.

Multiple return values return each one independently, reducing the amount of data that must be unpacked from a packed structure. It also eliminates the requirement to return data pointers.

Here is an example of error handling support of Go when doing any Operation.

package main
import (
    "fmt"
    "errors"
)
func fun(a int) (int, error) {
    if a == 0 {
        return 0, errors.New("Zeros are not allowed")
    } else {
        return a * 2, nil
    }
}


func main() {
    a, e := fun(0)
    if e != nil {  // checking error here
        fmt.Println("Error Detected!!!")
    } else {
        fmt.Println(a)
    }  
    // output:
    // Error Detected!!!
}

Frequently Asked Questions

What is the need for skipping return values?

If you initialise a variable but don't utilise it, the Go compiler will throw an error. The error will be very annoying if you keep all return values in variables but never utilise them.

This issue can be entirely avoided by using the blank identifier to bypass the variables.

Can a function return multiple values?

No, a function cannot have two returns; the first return will terminate the function, requiring you to build an object. In the case of Golang, this is achievable.

In Golang, what does panic() do?

In Go, the panic() function is equivalent to exceptions raised at runtime when a problem occurs. When a program encounters an unexpected error, panic() is raised, or the programmer throws the exception on purpose to handle specific errors.

In Golang, what is defer?

The defer keyword in Golang is used to postpone the execution of a function or a statement until another function returns. Defer, in simple terms, moves the execution of a statement to the end of a function.

Conclusion

This article has discussed the definition, declaration examples, and features and uses of the Golang Function returning multiple values. We also discussed the types of multiple values returned by Functions.

You can learn related concepts like Object-oriented paradigmsoperating systems, classesinheritance, etc at the Coding Ninjas Studio blogs vertical.

We hope this article has helped you. You can check out this article on Exploring the dynamics of Golang. To understand the usefulness of Golang, read this article Why Golang is so famous among engineers. 

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

Live masterclass