One of the strengths of Go is the ability to return multiple values from a function. As a long-time Java programmer I’ve envied languages with muttiple returns for a long time. Here’s a quick summary of the feature:
Quick example: to return multiple values, use the classic return statement:
return value1, value2
And to get those return values from a function, you can write:
var1, var2 := someMultipleReturnFunction()
The great thing about this system is that you can ignore a return value if you don’t need it. For example, if you need to skip the first return value:
_, var2 := someMultipleReturnFunction()
Which brings me to the original reason for this blog post. I was writing a Go application, when a build failed due to the error not enough arguments to return. The problem was that I had multiple return statements within a function, and one of the statements declared only one return value, instead of the two return values that the function declared.
The easy fix? Simply declare nil to pad out the “missing” return value. So the return statement became:
return var1, nil
Easy, quick, and painless.