Golang - Multiple Return Values

Learn via video courses
Topics Covered

Overview

A function is a reusable block of code used in a programming language. It has function body, Arguments, and return types. Golang returns multiple values with its functions Implementation. In this article, we will understand more about Multi-value returns in Golang.

Introduction

A Programming function is a line of codes that performs a single task. Functions help in the division of our program into smaller, modular portions. It also eliminates repetition and makes the code reusable.

Below is a generic function skeleton.

function_name: It is the name of the function.

parameters: It contains information regarding the input argument data types.

return_type: It includes the types of values that the function returns.

Functions in Golang

Example to create and invoke a Golang function.

Output:

Example for Golang Function : here

Multiple Return Type

In Golang, You are given the functionality to return multiple values from a function. you can just return as many values as you want and consume them with a comma-separated variables list as shown in the syntax.

Syntax:

Example of Multiple Return Type

Let's create an example where a Golang function returns the next 3 integers of that of the input parameter.

Output:

Multiple return Type example : here

Named Multiple Return Type

Golang allows us to name our return types. They are treated as variables defined at the top of the function. A return statement without arguments returns the named return values, As shown in the example. This is also known as a naked return.

Let's modify our example with getNextThreeValues() function to a Named multiple return type example.

Output:

Named multiple return type example: here

Conclusion

  • Described the concept of returning multiple values using a Golang function.
  • Implemented examples showing the use of multi-return values.