-3

exported:

var MyFunction = func(){}
function MyFunction func(){}

unexported:

var myFunction = func(){}
function myFunction func(){}

I read the var functionName = function() {} vs function functionName() {} this is about Javascript.

The reason I am considering changing from function myFunction func(){} to var myFunction = func(){} is the later makes me easier to do my unit test.

So I am wondering if there's anything I need to pay attention to before making this change.

sfdcnoob
  • 759
  • 1
  • 8
  • 15
  • Is your question here asking for an exhaustive list of the differences in behavior between the two ways of defining a function named `myFunction`? I think that can be provided; just checking. – Jesse Amano May 24 '19 at 21:32
  • 2
    The var approach is not idiomatic and godoc will not display the "functions" as functions; – Cerise Limón May 24 '19 at 21:58
  • yes `var MyFunction = func(){}` is very JavaScript-y. When in doubt, go with the simpler more declarative form. – colm.anseo May 25 '19 at 00:51
  • Why do you believe using `var` will help with unit tests? This is a code smell to me. I suspect your unit test approach can be improved. – Flimzy May 25 '19 at 11:58

1 Answers1

0

The chief distinction between the two forms is that they differ not only in syntax but rather in their semantics:

  • The "normal" form which uses the func name (...) form creates a regular named function.
  • What you call "create a function using var" is actually creating a so-called anonymous function and assigning its value to a variable.

The difference is that in Go, anonymous functions behave as closures, while regular functions do not.

A closure is a function which "captures" any variables from its outer lexical scope which are used in the function's body (while not being shadowed by local variables and function arguments there).

The distinction may not be apparent when either form it used at the top level of a package — that is, outside of any function's body, — since the outer scope in this case is the package's global variables, but inside other functions the distinction is apparent: the "normal" form simply cannot be used.

Other distinction is that you can replace the value in a variable containing a function value, while you cannot do the same with the normal function.

Still, if we're talking about the top-level code, the suggestion offered by Flimzy holds: in production Go code, having global variables containing function values is code smell until it can be proved to be otherwise.

kostix
  • 43,267
  • 10
  • 69
  • 137