Go, Software Development

Golang – Return multiple values from a Function

In Golang, we can return more than one value from a function, but this feature is not unique to the programming language. Other languages can do this too.

Golang Function Declaration To Return Multiple Values

Golang’s ability to return multiple values from a function is nothing new. We can return similar data types like an array, a tuple, an instance of a class, or a struct in other languages. For example, we can produce an object with various properties in OOP programming languages like Java. Meanwhile, we can also return an instance of struct with multiple fields like C/Rust.

The general syntax of functions to return multiple values is as follows. We have the MyFunction function with a list of parameters and return values. Within these lists, we separate the values using commas.

Golang Sample Function That Returns a Tuple

The codes below demonstrate his built-in facility. Here we have the GetDomainDetails function that returns two string values. Notice we use the colon-equal-sign for locally-scoped variables, e.g., function local variables. Although the values are not within parentheses, they are still tuples.

Note that the order of the variables that receive the values from the function matter in Golang. In our sample codes, the domain (turreta.com) comes first before the title (projecting knowledge).

When we run the codes in the command-line window, we get the following output.

Download Golang the codes

The complete codes that show a Golang function returns multiple values are available at this link.

Although this feature is not totally useless, it is not ideal specially for code readability because we could get the assignment wrong. A better approach is to use a struct with fields in Golang and explicitly assign the values to them. That way, we can avoid inadvertently assigning values to the wrong variables.

We tested the codes using Golang 1.18 in Windows 10.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like