Empty return in func with return value in golang

Go's return values may be named. If so, they are treated as variables defined at the top of the function.

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
   return
}

func main() {
    fmt.Println(split(17))
}

https://tour.golang.org/basics/7


When you have a named return value (err here):

func  Insert(docs ...interface{}) (err error) {

This creates a function-local variable by that name, and if you just call return with no parameters, it returns the local variable. So in this function,

return

Is the same as, and implies,

return err

This is detailed in the tour and in the spec.


The function uses a "named" return value.

From the spec on return statements:

The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.

Regardless of how they are declared, all the result values are initialized to the zero values for their type upon entry to the function. A "return" statement that specifies results sets the result parameters before any deferred functions are executed.

Using named returns allows you to save some code on manually allocating local variables, and can sometimes clean up messy if/else statements or long lists of return values.

func a()(x []string, err error){
    return
}

is really just shorthand for

func a() ([]string,error){
  var x []string
  var err error
  return x,err
}

Its a bit shorter, and I agree that it may be less obvious.

Named returns are sometimes needed, as it allows things like accessing them inside a deferred function, but the naked return is just syntactic sugar as far as I can tell, and is never strictly required.

One place I see it commonly is in error return cases in functions that have many return values.

if(err != nil){
   return
}
return a,b,c,nil

is easier than

if(err != nil){
   return nil,nil,nil,err
}
return a,b,c,nil

when you have to write it a bunch of times. And you don't have to modify those returns if you change the signature to have additional "real" return values.

Most places I am using them in the codebase I just searched, they definitely seem to be hiding other smells, like overly complex multi-purpose functions, too deep if/else nesting and stuff like that.

Tags:

Go