SOLVED: How to return multiple values in GoLang func() | GoLinuxCloud (2023)

Table of Contents

Advertisement

In this article, we are discussing how to return multiple values using a function in Go.

Golang has inbuilt features which support multiple return values. In a function return statement is used to return multiple values. The type of the return values must match the type defined for parameters.

Golang function syntax to return one or more values

A function can have multiple numbers of return values. Through the use of inbuilt features in Go, this mechanism is supported effectively.

Below is a syntax used to return multiple values in a function.

func funcName(x paramType1,y paramType2,--)(returrnType1, returrnType2,…){}

Return single value in the golang function

The return types and values can be declared in numerous ways as we discussed below. When we are returning a value, we can also declare the type of the value to be returned as shown below.

package mainimport ("fmt""os""strconv")func salaryIncrement(salary int64) int64 {return salary * 3}func main() { inputValue,_ := strconv.Atoi(os.Args[1])results := salaryIncrement(int64(inputValue))fmt.Println(results)}

Output:-

$ go run main.go 300900

Explanation:-

salaryIncrement(salary int64) int64{}:-It a function which accepts input of a value of type integer 64 and returns value of the same type.

Advertisement

main():- We are using os package to read value arguments without hardcoding the values to the function. Fmt package to print out the results.

Return multiple values in the golang function

Go functions can return multiple distinct values, which saves you from having to create a dedicated structure for returning and receiving multiple values from a function. You can declare a function that returns four values (twointvalues, onefloat64value, and onestring) as follows:

func aFunction() (int, int, float64, string) {}

Example-1: Return multiple values with the same return type

In this example we will use define the same type for both the values we intend to return in our glang function.

package mainimport ("fmt""os""strconv")func multDivisionValue(value int64) (int64, int64) {return value * 2, value / 2}func main() {//elementsinputValue,_ := strconv.Atoi(os.Args[1])multValue, divValue := multDivisionValue(int64(inputValue))fmt.Println(multValue, divValue)}

OutPut:-

$go run main.go 36 1

Explanation

multDivisionValue():- is a function that accepts a single value of type integer 64 and it's used to multiply the value with 2 and perform division as well using 2 as a divider. It returns two values of both type integer 64.

main():- The os package is used to get value from terminal to inputValue, which is later passed to multDivisionValue() function, and results from the function are passed to multValue and divValue respective. These values are printed out using the fmt package.

Example-2: Return multiple values with different return types

In this example we will define different return type for both the values in our golang function.Example of the different return types.

package mainimport ("fmt""os""strconv")func integerFloats(value int) (int, float64) {return value % 2, float64(value) * 3.05}func main() {// pass value from terminalvalue, _ := strconv.Atoi(os.Args[1])a, b := integerFloats(value)fmt.Printf("Modulus of value is %v, floating value is %f", a, b)}

OutPut:-

$ go run main.go 30Modulus of value is 0, floating value is 91.500000%

Explanation:-

We have defined return type as int and float64 for our intergerFloats function. We are using the os package to read user’s input. We pass the value to the function and calculate the modulus of the value and then convert the value to a floating 64-bit then multiply the value by 3.05.

Ignore one or more values returned from golang functions

Golang as inbuilt features that allows one to initialize a variable but do not use it, Go has a literal, the hyphen (-), used to replace data thus causing the compile to skip it completely. the Go compiler will give an error. It’s not a good practice in case you store all return values in a variable.

An Example of skipping return value in Go

// main.gopackage main import ( "fmt") func skippingReturn(value int) (int, int) { return value*2, value*4} func main() { result, _ := skippingReturn (23) // Observe the skip operator used to ignore single value from skippingReturn fmt.Println(result) }

OutPut:-

$ go run main.go 46

Explanation:-

ALSO READ: What is the zero value for time.Time in GO? [SOLVED]

skippingReturn():- Function accept one input value of type int and return 2 output of type int. It process the input value by multiplying by 2 and 4 as return values.

main():- in this function we are interested in only one subset of returned value thus a blank identifier, _ is used to omit the second value. Thus, using fmt package to printout the results on terminal.

Multiple return value with Error handling in Go

Go support multiple return value in error handling. These errors are returned during performance of operation such as reading a file, reading user input etc. Below is an example of multiple return value with error handling in Golang

An example of error handling in Go

package mainimport ( "errors" "fmt" "os" "strconv")func errorFun(value int64) (int64, error) { if value == 0 { return 0, errors.New("Zero not allowed") } else { return value * 2, nil }}func main() { val, _ := strconv.Atoi(os.Args[1]) x, y := errorFun(int64(val)) if y != nil { // check error here fmt.Println("Zero not allowed, error") } else { fmt.Println(x) }}

output:-

$ go run main.go 0Zero not allowed, error

Explanation:-

The (int64, error) in this function signature shows that the function returns 2 outputs int64 and an error. We have used zero digits as our error identity, once user input is equal to 0 then the error will be triggered, and displayed. The errorFun()function receives value of int64 type. If condition equates the value entered and checks if is equal to 0, else it multiplies the value by 2 and returns multiples of value by 2 and nil as an error.

ALSO READ: Golang cast to string from different data types [SOLVED]

In main(), we are using the os package to read users' input which is of type string and we convert it to an integer by using the strconv package. x, y:= errorFun(int64(val)) Here we use the 2 different return values from the call with multiple assignments and convert val into int64 by wrapping value into int64(val). if clause is used to validate the response from errorFun().

Named return values in Go

Unlike C, Go allows you to name the return values of a Go function. Additionally, when such a function has areturnstatement without any arguments, then the function automatically returns the current value of each named return value in the order in which it was declared in the definition of the function.

These names should be used to document the meaning of the return values.

package main import ( "fmt" "os" "strconv" ) func namedMinMax(x, y int) (min, max int) { if x > y { min = y max = x } else { min = x max = y } return } 

Output:-

$ go run main.go 2 GoLinuxCloud

Explanation:

In this code segment, you can see the implementation of thenamedMinMax()function, which uses named return parameters. However, there is a tricky point here: thenamedMinMax()function does not explicitly return any variables or values in itsreturnstatement. Nevertheless, as this function has named return values in its signature, theminandmaxparameters are automatically returned in the order in which they were put into the function definition.

ALSO READ: Remove fields from struct or hide them in JSON [SOLVED]

They can harm readability in longer functions.

Summary

  • Multiple return values are extremely useful when checking errors.It makes the program flow easier since you are checking the errors in a step-by-step manner.This omits the need for complicated and nested error-checking and other problems.
  • Multiple return values return each of them separately so it reduces the need of unpacking data from a packed structure.
  • It also reduces the need of returning pointers to data.

References

multiple return value in Go
Multiple return value in go

Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated: 17/09/2023

Views: 5727

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.