myvar := func()
outside of a function definition, complaining that it is a
non-declaration statement.
var myvar = func()
causes no problem, and is recommended e.g. for the flags package.
Since the former is really a shorthand for the latter (and it seems,
has no other usage), should it be considered a non-declaration
statement? Or is there a good reason to force the use of 'var' outside
of functions? It seems a strange and unnecessary restriction.
(I know what the go specification says, and it only confused me.
ShortVarDecl "is a shorthand for a regular variable declaration with
initializer expressions but no type", but "Short variable declarations
may appear only inside functions" with no reason given.)
--
Scott Lawrence
> The compiler doesn't like
>
> myvar := func()
>
> outside of a function definition, complaining that it is a
> non-declaration statement.
>
> var myvar = func()
>
> causes no problem, and is recommended e.g. for the flags package.
> Since the former is really a shorthand for the latter
It's not "really" a shorthand, it's "like" a shorthand. They're subtly different in a number of cases. For instance,
var a, b int = 3
cannot be recreated by a := statement.
> (and it seems,
> has no other usage), should it be considered a non-declaration
> statement? Or is there a good reason to force the use of 'var' outside
> of functions? It seems a strange and unnecessary restriction.
At the top level, var (or const or type or func) is necessary: each item must be introduced by a keyword for ur-syntactic reasons related to recognizing statement boundaries. With the later changes involving semicolons, it became possible, I believe, to eliminate the need for var in some cases, but since const, type, and func must remain, it's not a compelling argument.
> (I know what the go specification says, and it only confused me.
> ShortVarDecl "is a shorthand for a regular variable declaration with
> initializer expressions but no type", but "Short variable declarations
> may appear only inside functions" with no reason given.)
It's a bit of history and a bit of simplicity, at the cost of apparent (but partially fallacious) consistency.
I accept the criticism that there are too many ways to declare a variable.
-rob
Ok, that's a good excuse ;-)
--
Scott Lawrence