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.
1 2 3 | func MyFunction(parameter-list) (result-list) { body } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | package main; import "fmt" func GetDomainDetails() (string, string) { return "turreta.com", "projecting knowledge" } func main() { domain, title := GetDomainDetails() fmt.Println(domain) fmt.Println(title) } |
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).
1 | domain, title := GetDomainDetails() // domain is set to the first value, while title the second value |
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.