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?
Short declaration operator can be used when at least one of the variable in the left-hand side of := operator is newly declared. A short variable declaration operator behaves like an assignment for those variables which are already declared in the same lexical block.
No, there is no shorthand for this. := always assigns to variables in the current (innermost) scope, creating new variables if necessary. To assign to any variables outside the current scope, you must use = instead of := , and in the case of multiple-assignment this means that all variables must be pre-declared.
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword ( var , func , and so on) and so the := construct is not available.
Using short variable declaration you are allowed to declare multiple variables of different types in the single declaration. The type of these variables are determined by the expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With