Table of contents
1.
Introduction
2.
Definition
3.
Examples
3.1.
Code 1
3.2.
Code 2
4.
Features
5.
Uses
6.
Frequently Asked Questions
6.1.
In Golang, what does panic() do?
6.2.
In Golang, what is defer?
6.3.
In Go, how do you use recover?
6.4.
What do Go routines involve?
7.
Conclusion
Last Updated: Mar 27, 2024

Named Return Values in Go

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

Introduction

Go was created as a systems programming language to help Google speed up systems development. It is currently used for Web development, mobile development, parallelism, etc.

Out of impatience with the pace of software development, PikeThompson, and Robert Griesemer decided to try their hand at creating a new language.

In this article, we will discuss one of the essential features of Golang. We will learn the definition, examples, features, uses, and the default values of the named return values in Golang.

Definition

In Golang, the return parameters of functions can be given names in the function signature or definition. It removes the need to provide the variable's names in the return statement.

When utilising named return parameters, the only way to return the result to the caller is to use the return keyword at the end of the function. When a function must return multiple values, this idea is commonly employed.

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

func func_name(p1 paraType 1, p2 paraType 2, p3 paraType3,......)(Result 1 dataType, Result 2 dataType, Result 3 data Type,.....){
     //  some code…
return
}
  • func: func is a keyword in Go to create a function.
  • func_name: It denotes the name of the function.
  • (p1 paraType 1, p2 paraType 2,......): It specifies the function parameters' name and type.
  • (Result 1 dataType, Result 2 dataType,.....): It's a list of named return arguments with their types. We can use multiple return arguments at once.
  • return: Return is the keyword without any arguments.

Initially, the values of named return parameters are set to zero.

The names are not compulsory. However, they can help with documentation. When utilized correctly, Named return parameters can also help clarify and clean up the code when used correctly.

Examples

After the function parameters, we can specify named return variables in round brackets. Here is an example of a named return type in Go.

Code 1

package main
import "fmt"
func example(A, B, C int) (a, b, c int) {
    a = A + 5
    b = B + 10
    c = C + 5
    return
}
func main() {
    A, B, C := example(10, 100, 1000)
   fmt.Println(A, B, C)
}

The output of the above program:

15 110 1005

Code 2

package main
import "fmt"
func rect(l int, b int) (area int) {
var parameter int
parameter = 2 * (l + b)
fmt.Println("The Parameter: ", parameter)
area = l * b
return // Return statement without specified variable name
}
func main() {
fmt.Println("The Area: ", rect(10, 20))
}

The output of the above program:

The Parameter: 60
The Area: 200

Features

  • We don't have to manually allocate the return variables since they're named as result types; they're automatically initialised to zero when the function runs.
  • Named return parameters serve as excellent implicit documentation. We can tell what the function returns right from its signature, and naming things makes it easier to understand the code.
  • If a function has numerous exit points, we don't need to write all the parameters; we simply return (called bare return). We can still list the returned values directly, and we should probably do so to make the code easier to read.

Uses

As various programmers have pointed out, the advantage of named return values is that they can be used in closures (i.e., defer statements). As a result, the named return value in a function called as a result of a defer statement can be accessed and acted correctly.

Let’s consider an example named myFun():

func myFun(msg string) (i int, e error) {
i = 13
defer func() {
if r := recover(); r != nil {
e = fmt.Errorf("Recovered Error: %v", r)
}
}()
if msg == "panic" {
panic("Panic!!")
}
i = 23
return
}

We create a deferred function call to call recover() and set e to the recovered error value.

If the string parameter msg equals panic, the panic() function is called.

Otherwise, we call return and set the value of i to 23.

Now, if we call the function with i as e:= myFunc("don't panic"), we get the following result:

  • i: 23
  • Err: <nil>

If we call the function as i, e = myFunc("panic"), we get the following result:

  • i: 13
  • Err: Recovered Error: Panic!!

We must utilize the named return values technique here because the return values from a deferred function call are discarded.

For this use-case, named return values allow application designers to specify desirable safe/default values that would eventually be returned from the panicked function.

 

Read Also - Difference between argument and parameter

Frequently Asked Questions

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 presented, 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.

In Go, how do you use recover?

The recover function in Go is used to deal with panic. It's a built-in function in the Go language, defined in the built-in package. This function is used primarily to retake control of a panicking Goroutine.

What do Go routines involve?

Goroutines are functions or procedures that run in parallel with others. Goroutines are similar to lightweight threads. When compared to a thread, the cost of starting a Goroutine is negligible. As a result, Go applications frequently run thousands of Goroutines simultaneously.

Conclusion

This article has discussed the definition, examples, features, and uses of the Golang Named return values. We hope this article has helped you understand the concept of named return Values in Golang.

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

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