golang

Examples of Returning Multiple Values in Golang

Here’s an article in Go that showcases multiple examples of returning multiple values from a function. Go’s ability to produce numerous results from a function is one of its noteworthy features. This capability allows the Go users to write a concise and expressive code by efficiently returning multiple pieces of data. In this article, we will get to know about the multiple examples that showcase the versatility and usefulness of returning multiple values in Go. Let’s consider the examples from the basic one to the complex one.

Example 1: Return Multiple Values of the Same Type in Golang

Go can significantly return multiple values of the same type using the function. The simple program is given in the following where multiple values of the same data type are returned:

package main

import "fmt"

func main() {
    val1, val2  := f1()
    fmt.Println(val1)
    fmt.Println(val2)
}
func f1() (int, int) {
    return 8, 9
}

Here, we just import the required package for the program. After that, we simply define the main() function where there are two variables declared – “val1” and “val2”. These variables are not assigned with any values yet; we initialize them with the results of the f1()function.

Then, the “val1, val2 := f1()” employs the f1()function and assigns the two returned values to the “val1” and “val2” variables, respectively. This syntax is referred to as “multiple assignment” in Go. Next, the f1() function is defined. It returns two integers (int, int) and simply returns the values of 8 and 9.

The multiple return values are retrieved in the following output from the previous program execution:

Example 2: Return Multiple Values in Golang Using the GetNextThreeValues() Function

Additionally, we can use the function called getNextThreeValues() to return multiple values. This function returns the next three integer values in a sequence. Consider the following program to return the next three values using the getNextThreeValues() function:

package main

import "fmt"

func getNextThreeValues(m int) (int, int, int) {
   return m + 1, m + 2, m + 3
}

func main() {

   inputValue := 5
   fmt.Println("First value : ", inputValue)

   n1, n2, n3 := getNextThreeValues(inputValue)

   fmt.Print("Three values next : ")
   fmt.Println(n1, n2, n3)
}

Here, we add the package using the “import” keyword. Then, we define the getNextThreeValues() function which takes an integer parameter of “m.” It returns three integers which are “m + 1”, “m + 2”, and “m + 3”, respectively. The function calculates and returns the next three values after “m”. After that, the main() function is called, and the value of “5” is declared and assigned to the “inputValue” variable. Again, we call the getNextThreeValues() function with the “inputValue” as an argument and assign the three returned values to the “n1”, “n2”, and “n3” variables, respectively, which represent multiple assignment.

The result shows the first value along with the next three values in order:

Example 3: Return Multiple Values of Different Types in Golang

It is also feasible for a function to return numerous values of different types. This feature is commonly used when a function needs to provide multiple data pieces of different types. With the help of the following program, returning multiple values of different types are illustrated:

package main

import (
"fmt"
"os"
"strconv"
)

func NumFloats(val int) (int, float64) {
return val % 2, float64(val) * 3.14
}

func main() {

val, _ := strconv.Atoi(os.Args[1])
x, y := NumFloats(val)
fmt.Printf("Modulus is %v, floating result is %f", x, y)
}

Here, we import the “os” package to handle the command-line arguments and the “strconv” package for string conversions along with the “fmt” package. After that, we deploy the NumFloats()function which takes the “val” integer as input and returns two values: an integer that represents the modulus of “val” when divided by the value of 2 and a floating-point number that is the result of multiplying val by “3.14”.

Next, we establish the program’s main() function where we retrieve the command-line argument using os.Args[1] which represents the second element of the os.Args slice. Then, we convert the argument to an integer using strconv.Atoi() and assign the result to the “val” variable. Next, we call the NumFloats() function with “val” as the argument and assign the returned values to “x” and “y”.

The output displays the computed modulus and floating result for the value of 5:

Example 4: Give the Names to Return Multiple Values in Golang

However, we can give names to a function’s return values. These named return values act as variables within the function body and are automatically returned at the end of the function.

package main

import "fmt"
func Newfunc(k, l int)( rect int, sq int ){
rect = k*l
sq = l*l
return
}

func main() {
var a1, a2 = Newfunc(4, 8)
fmt.Printf("Rectangle Area: %d", a1 )
fmt.Printf("\nSquare Area: %d", a2)
}

Here, we define a function called “Newfunc” that takes two integer parameters, “k” and “l.” Inside the function, we calculate the area of a rectangle by multiplying “k” and “l” and assign it to the “rect” variable. We also calculate the area of a square by multiplying “l” with itself and passing it to the “sq” variable.

Finally, the function returns the values of “rect” and “sq.” Next, we create the main() function where we deploy the Newfunc() function with the arguments of 4 and 8. It assigns the returned values to the “a1” and “a2” variables, respectively.

Thus, the calculated area of a rectangle and a square are displayed in the following which are based on the provided dimensions:

Example 5: Return Multiple Values with Exception Handling in Golang

Moreover, the functions can return multiple values along with an error to handle exceptional cases. This is a common pattern in Go which allows us to indicate and handle the errors in a structured way.

package main

import (
   "errors"
   "fmt"
   "os"
   "strconv"
)

func errFun(myValue int64) (int64, error) {
   if myValue == 0 {
      return 0, errors.New("Zero not acceptable")
   } else {
      return myValue * 4, nil
   }
}

func main() {
   v1, _ := strconv.Atoi(os.Args[1])
   m, n := errFun(int64(v1))
   if n != nil {
      fmt.Println("Zero not acceptable, error")
   } else {
      fmt.Println(m)
   }
}

Here, we create a function named errFun() that accepts an “int64” integer as an argument. Inside the function, we examine if the input value is zero. If so, the function returns an error using errors.New() to create a new error object with the “Zero not acceptable” message. Otherwise, it returns the input value multiplied by 4 and a “nil” error.

After that, we retrieve the command-line argument using os.Args[1] and convert it to an integer using strconv.Atoi. We then employe the errFun() function with the converted value as an “int64” argument and assign the returned values to “m” and “n.” Next, we check to see if the “n” error is not “nil”, which would mean that the errFun() method ran into trouble.

As we provided the “0” value in the terminal, the function returns the following error:

Conclusion

Returning multiple values from functions in Go provides a flexible and concise way to convey multiple pieces of information. We covered the scenarios involving multiple integers, values of the same type and different types, and named return values. Also, the approach to handling multiple return values’ errors was covered. With these examples, we now have a solid foundation for utilizing and understanding this powerful feature of Go.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content