This is allowed:
package main
var a = 3
...
But this isn't:
package main
a := 3
...
Why not? Why couldn't short variable declaration outside a function be treated regular declaration without a type? Just to simplify parsing?
This is allowed:
package main
var a = 3
...
But this isn't:
package main
a := 3
...
Why not? Why couldn't short variable declaration outside a function be treated regular declaration without a type? Just to simplify parsing?
According to Ian Lance Taylor in this thread shortly after the public announcement:
At the top level, every declaration begins with a keyword. This simplifies parsing.
To quote from The Go Programming Language Specification:
Short variable declarations may appear only inside functions. In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables.
You can think of var
statement like const
, type
, and func
, in the package level you have to specify what's kind of statement you are declaring.
Well , it's not a real shorthand , a, b := 12
can't compile, var a,b = 12
do.
Outside a function, every statement must begin with a keyword (var, func, and so on), and so the :=
construct is not available.
See here. Hope it helps.