If you use named return values, you need to be aware of one severe misfeature in Go: blank (sometimes called naked) returns. If you have named return values, you can just write return without specifying the values that are returned. This returns the last values assigned to the named return values. Rewrite the divAndRemainder function one last time, this time using blank returns:
func divAndRemainder(num, denom int) (result int, remainder int, err error) {
if denom == 0 {
err = errors.New("cannot divide by zero")
return
}
result, remainder = num/denom, num%denom
return
}
Using blank returns makes a few additional changes to the function. When there’s invalid input, the function returns immediately. Since you assigned no values to result and remainder, their zero values are returned. If you are returning the zero values for your named return values, be sure they make sense. Also, note that you still have to put a return at the end of the function. Even though this function is using blank returns, it still returns values. Leaving out return is a compile-time error.
At first, you might find blank returns handy, since they allow you to avoid some typing. However, most experienced Go developers consider blank returns a bad idea because they make it harder to understand data flow. Good software is clear and readable; it’s obvious what is happening. When you use a blank return, the reader of your code needs to scan back through the program to find the last value assigned to the return parameters to see what is actually being returned.
Warning
If your function returns values, never use a blank return. This can make it very confusing to figure out what value is actually returned.