Empty return in func with return value in golang [duplicate]

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.

Leave a Comment