Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't short variable declaration allowed at package level in Go?

Tags:

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?

like image 251
Trevor Dixon Avatar asked Sep 17 '13 15:09

Trevor Dixon


People also ask

Where can the short variable declaration used in Golang?

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.

Can short declaration := be used for defining global variables in go?

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.

Is it true that short variable declaration := can be used only inside a function?

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.

Can you declare multiple types of variables in single declaration in go?

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.


1 Answers

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.

like image 88
Gustavo Niemeyer Avatar answered Sep 19 '22 12:09

Gustavo Niemeyer