The Go programming language makes it possible and easy to return multiple values from functions. While most programming languages limit the number of values you can return to just one, with Go, you can return two, three, or really any number of values that will solve your problem.
Let’s take a look at a couple of examples.
Return One Value from a Go Function
The first one we’ll start with is just return a single value.
package main
import "fmt"
func returnOne() string {
return "Return One"
}
func main() {
result := returnOne()
fmt.Println(result) // "Return One"
}
This is a classic example. In our returnOne()
function we don’t take any
parameters and return just one value that is of type string.
Return Two Values from a Go Function
Let’s turn it up a notch and return two values.
package main
import "fmt"
func returnTwo() (string, string) {
return "Value One", "Value Two"
}
func main() {
resultOne, resultTwo := returnTwo()
fmt.Println(resultOne, ResultTwo) // "Value One Value Two"
}
A couple things change. First, we have to wrap the values we expect back in
parenthesis and declare the type we expect. Second, we also have to create two
variables in our main()
function to capture the two return values sent back.
If we were to omit one, our program would not compile.
We have to do something with all the returned values from a function. If we aren’t going to use the data from a returned value we could ignore it but declaring the variable with an
_
. This would allow us to discard the value, while still accounting for it.
package main
import "fmt"
func returnTwo() (string, string) {
return "Value One", "Value Two"
}
func main() {
// Discard the second value returned
resultOne, _ := returnTwo()
fmt.Println(resultOne) // "Value One"
}
Alternatively, we could have discarded the first value by using the _
for the
first variable declaration.
Return Three or More Values from a Go Function
For our last example, we’ll return three values. We’ll also mix and match the return types to make this example a little more interesting.
package main
import "fmt"
func returnThree() (string, int, bool) {
return "The year is:", 2020, true
}
func main() {
resultOne, resultTwo, resultThree := returnThree()
fmt.Println(resultOne, resultTwo, resultThree) // "The year is: 2020 true"
}
As you can see, we can return as many values from our Go functions as needed to do the job. In practice, you’ll often see functions return the expect value and and error.
Having the ability to return multiple values for our functions unlocks many possibilities but you should still be cautious to not write functions that do too many things. It’s always better to break up functionality into smaller pieces that are more testable and easier to reason about than have monolithic functions that attempt to solve multiple problems. Just because you can, doesn’t mean you should.