Go Multiple return value

In this article, we are going to demonstrate how to return multiple distinct values of a single function in Go. This is a very handy feature in comparison to most programming languages that support returning a single value from a function. In most programming languages if you want to return multiple values it can be accomplished by using tuple, hash, model or other types. Go is one of the few languages that natively support multiple return values. A good example in Go is the strconv.Atoi() function which converts a string into an int value.

Consider the following code example:

i := 2 // short declaration (1)
value, err := strconv.Atoi(i) //result the int value and error message (in case it failed the conversion)

In the first section (1), a short declaration operator is used which implements a short variable declaration.

Functions that return multiple values

Consider the following example:

func multiplyValue(value int) (valuePassed int, multiplyValue int) {
  valuePassed = value // 1
  multiplyValue = value * 10 // 2
  return
}

This example illustrates how two int values can be returned through a single function. In the example above, an int value is passed as a parameter and it will return the int value passed (1) and another int value which is the parameter multiplied by 10 (2).

Return more than 2 values

In Go, a function can return more than two values compare to the example above. This saves you from having to create a dedicated structure in order to receive more than two values at ones from a function. Consider the following example which returns four values, two int values, a float64, and a string:

func returnFourValues() (int, int, float64, string){
  return 1,2,1.0,"string value"
}

Practical example

For this topic, we develop a simple app that covers this feature. In this example, we are going to be using the following packages: fmt, os and strconv.

Fmt

The fmt package implements formatted Input/Output (I/O) which makes it possible to print text on the console.

For an in-depth explanation, read the Golang fmt Package documentation.

Os

The os package provides a platform-independent interface to operating system functionality. It is based on a Unix design, but the error handling is based on Go. For more information about this package, read the documentation.

Strconv

The strconv package provides string conversions functionalities based on the Go basic types. For more information about this package see, read the strconv package documentation.

Return two string values

In this example we are going to implement a simple function that returns multiple string values, just like the following function below:

func multiReturns() (value1 string, value2 string) {
  value1 = "return string value 1" (1)
  value2 = "return string value 2" (2)
  return
}

In the example above two string values are being returned which are value1 and value2. Value1 and value2 are assigned in the function body itself see 1 and 2. The return keyword without any arguments automatically signals the function to return the current values of each named return value in the order in which they were declared in de definition of the function. This feature in Go is well known as Named returned values.

Note: It is highly recommended to use this feature as much as possible since it can save you from different types of bugs.

Return two int values

The function described in the previous example return two string values. In this next example we are going to implement a function that returns two int values:

func multiplyValue(value int) (valuePassed int, multiplyValue int) {
  valuePassed = value
  multiplyValue = value * 10
  return
}

In this example, the function required one parameter and it will return the parameter valuePassed and the parameter multiply by 10 multiplyValue. The same way values can be assigned as described in the previous example.

Returning values of different types

In the following example, we will be implementing a function that returns multiple values (more than two) of different types:

func multiplyValueTypes(value int) (int, int, string) {
  return value, value * 10, "calculated"
}

Two int values and a string value is being returned by this function. As you can see in the function body the parameter is being assigned to the first return value of type int, the second return value is the parameter value multiply by 10 and lastly, a string value indicating that the values has been calculated.

Executing these Go functions

As you notice in the previous articles each Go app has a main function which is the main entry point of the application. In this case, it is no exception. To execute our sample app, we need to implement the main function. This is how the main function will look like:

func main(){

  (1)
  fmt.Println("\n|------------- Multi return ------------------|")
  value1, value2 := multiReturns() (1.1)
  fmt.Println("Value 1: "+value1,"\nValue 2: "+ value2) (1.2)
  fmt.Println("|---------------------------------------------|")

  (2)
  argument := os.Args (2.1)
  if len(argument) != 2 { (2.2)
     fmt.Println("The program need at least 1 argument to perform the   
     argument calculation") (2.3)
     return (2.4)
   }

  (3)
  value, err := strconv.Atoi(argument[1])(3.1)
   if err != nil {(3.2)
     fmt.Println(err) (3.3)// Error message
     return (3.4)
   }

  (4)
  fmt.Println("\n|------------- Multi return int ------------------|")
   valuePassed, valueMultiply := multiplyValue(value)(4.1)

   valueConvertedToString := strconv.Itoa(valuePassed)(4.2)
   multipliedValueConvertedToString := strconv.Itoa(valueMultiply) (4.3) 

   fmt.Println("Argument value (int): "+valueConvertedToString) (4.4)
   fmt.Println("Multiply argument (int): "+multipliedValueConvertedToString) (4.5)
   fmt.Println("|-------------------------------------------------|")

 (5)
   // This example demostrate how to handle multiple return values of different types
   fmt.Println("\n|------------ Multi return with multiple types --------------------|")
   passedValue, passedValueMultipliedBy10, taskResult := multiplyValueTypes(value) (5.1)
   valuePassedConvertedToString := strconv.Itoa(passedValue) (5.2)
   valueMultiplyConvertedToString := strconv.Itoa(passedValueMultipliedBy10) (5.3)

   fmt.Println("Passed (int) value : "+valuePassedConvertedToString)
   fmt.Println("Passed multiply (int) value : "+valueMultiplyConvertedToString)
   fmt.Println("Task result (string): "+taskResult)
   fmt.Println("|------------------------------------------------------------------|")
}

Code section 1

The first section of the main function is a simple function that returns two string values. This is the proper way to implement it in order to retrieve two string values from a single function in Go. Section 1.1 return the two string values. The line that follows prints the result on the console 1.2.

Code section 2

In this section, we are going to gather argument values passed (2.1) by using the os.Args function which provides access to raw command-line arguments. Before we can retrieve argument values we need to check if it’s not equal to nil, this means no argument values were passed (2.2). In case it is equal to nil, the program will print a message on the console (2.3). Lastly, the return keyword terminates the execution of the program (2.4).

Code section 3

In the third section, we will be converting the argument int value at index 0 (index 1 in os.Args) into a string (3.1). The line that follows check if any error has occurred during the conversion process (3.2). Note that the strconv.Atoi is an internal Go function that returns multiple values. In case an error occurs, it will be printed on the console (3.3). Just like the previous section, the return keyword terminates the program if that is the case (3.4).

Code section 4

This section looks like the previous section, but in this case, we are dealing with two int values being returned. We will be retrieving multiple int values from our custom multiplyValue function (4.1). In this case, we must convert the int into a string by using the strconv.Itoa function(4.2). The same can be applied for the multiplied values (4.3). Section 4.4 and 4.5 just print the result on the console.

Code section 5

The last section will cover handling more than 2 return values from our custom multiplyValueTypes function that returns 3 values by passing an int value as a parameter (5.1). The result consists of two int and a string value. The first int value is the parameter (passedValue) which will be converted into a string value (5.2). The multiplied values will also be converted into a string (5.3). The rest of the codes is just printing the results on the console.  

Go to our repository for the full project.

To clone and run these source code in MacOS/OSX, read this article.

To clone and run these source code in Windows, read this article.

To clone and run these source code in Ubuntu (Linux), read this article.

Summary

Returning multiple values is a very handy Go feature that provides flexibility without any complex steps in between. Another handy feature is the Named returned values which can save you from different types of bugs. In this article, we cover some use cases you might encounter in practice such as returning multiple strings, int, and values of different types. Such a feature is very handy when it comes to building web services application in Go. Webservices is another topic that will be cover in a later article.

Relevant resources:

Follow us:

Leave a Reply

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